【问题标题】:How to read the cookie creation date (not expiration)如何读取 cookie 创建日期(未过期)
【发布时间】:2013-07-17 07:43:56
【问题描述】:

有没有办法在变量中存储 cookie 创建日期?我正在使用 jquery.cookie 插件。如果没有办法,我正在考虑将实际时间/日期作为值存储在 cookie 中。这可能是一个解决方案。

谢谢。

【问题讨论】:

  • 你能不能假设 cookie 的过期日期是设置时间后的 x 时间?所以你可以简单地通过(到期日期)-(x 时间)得到它?
  • @Puuskis,好主意,但是如何获得“x 时间”,这是这个问题所缺乏的。如果您有任何答案,请对此发表评论。
  • @SAM 如果您自己设置到期日期,您可以使用相同的时间来计算它。例如,如果所有 cookie 在 7 天后过期,您只需从该日期起减少 7 天。如果您不希望它们过期,请将它们设置为将来不相关但您仍然可以从中计算时间。
  • 这也是一个很好的解决方案。
  • 如果您在 chromium 浏览器中单击 url 前面的锁定图标,选择 cookie,并在存储的 cookie 中选择任何一个,您将看到 'created' 属性值在创建时给出。不确定添加 cookie 时浏览器是否在此处显式存储

标签: javascript jquery cookies jquery-cookie


【解决方案1】:
<!-- Output the DateTime that the cookie is set to expire -->
@Request.Cookies["YourCookie"].Expires.ToString()

但是,我不认为有一个属性可以获取创建日期,除非您将值本身作为附加值专门存储在 Cookie 本身中:

//Create your cookie
HttpCookie yourCookie = new HttpCookie("Example");
//Add an actual value to the Values collection
yourCookie.Values.Add("YourValue", "ExampleValue");
//Add a Created Value to store the DateTime the Cookie was created
yourCookie.Values.Add("Created", DateTime.Now.ToString());
yourCookie.Expires = DateTime.Now.AddMinutes(30);

//Add the cookie to the collection
Request.Cookies.Add(yourCookie);

您可以通过以下方式在您的页面中访问:

Created : @Request.Cookies["Example"].Values["Created"].ToString()
Expires : @Request.Cookies["Example"].Expires.ToString()

【讨论】:

    【解决方案2】:

    您确实必须将时间存储在 cookie 本身中。浏览器的 cookie API 不提供创建日期作为元数据。

    【讨论】:

    • 感谢您的回答。和我想的一样。
    猜你喜欢
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多