开发者

what is wrong with toDateString

开发者 https://www.devze.com 2023-04-06 20:19 出处:网络
Following is a script+HTML that tells the user his last visit to page. <html xmlns=\"http://www.w3.org/1999/xhtml\">

Following is a script+HTML that tells the user his last visit to page.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&开发者_StackOverflow社区gt;
<title>Cookie</title>
<script type="text/javascript">
window.onload = initLastVisit;

function initLastVisit() {
var now = new Date();
var last = new Date();
now.setMonth(now.getMonth()+6);
document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
document.getElementById("lastVisitedOn").innerHTML = document.cookie.split("=")[1];
}
</script>
</head>

<body>
<form>
<label>Enter your name&nbsp;&nbsp;<input type="text" id="name_field" /></label> <br/>
</form>
<h1 id="lastVisitedOn"></h1>
</body>
</html>

The statement that sets the cookie in the above script is : document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString(); . If in this i replace now.toGMTString() with now.toDateString() the expire time in the browser is "Expires when i close my browser" . Why is that ? It is ok with toGMTString . The expire date is in march 2012 as expected.


If you try them both in the console, you will see that they don't give the same resulting string at all:

(new Date()).toGMTString();
"Fri, 23 Sep 2011 16:33:01 GMT"

(new Date()).toDateString();
"Fri Sep 23 2011"

When you set a cookie you have to specify the time using GMT format, if you don't your browser fail to recognize the expiry time and consider that none was specified. When no expiry date is specified, cookie are created as "session cookie", which expires once the session end (eg you close your browser).

So when you use toDateString(), it is an invalid expiry format, your browser discards it and use its default value of creating a session cookie.


This is due to the format that is output from toDateString() which is not valid for specifying the expiry date for a cookie. * toDateString() - Fri Sep 23 2011 * toGMTString() - Fri, 23 Sep 2011 16:31:24 GMT

Due to the date string not being recognised the cookie will use default behaviour and expire at the end of the session.


toDateString does not produce a valid date- there is no time zone, and no time data included. toGMT string returns an unambiguous time.

I always wished for an integer time stamp, but a javascript timestamp is milliseconds-a thousand times bigger than the 'unix' seconds format.

There is always max-age.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号