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" />
<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 <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:
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.