toDateString 有什么问题

pro*_*eve 2 javascript cookies

下面是一个脚本+HTML,告诉用户他上次访问的页面。

<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&nbsp;&nbsp;<input type="text" id="name_field" /></label> <br/>
</form>
<h1 id="lastVisitedOn"></h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

上述脚本中设置cookie的语句是:document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();。如果在这里我用浏览器中的过期时间替换为now.toGMTString()关闭浏览器时过期”。这是为什么 ?没关系。预计到期日期为 2012 年 3 月。now.toDateString()toGMTString

Lep*_*eus 5

如果您在控制台中尝试它们,您会发现它们根本不给出相同的结果字符串:

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

(new Date()).toDateString();
"Fri Sep 23 2011"
Run Code Online (Sandbox Code Playgroud)

当您设置 cookie 时,您必须使用 GMT 格式指定时间,如果您不这样做,您的浏览器将无法识别到期时间并认为未指定到期时间。当未指定到期日期时,cookie 将被创建为“会话 cookie”,一旦会话结束(例如您关闭浏览器),该 cookie 将过期。

因此,当您使用 toDateString() 时,它是无效的到期格式,您的浏览器会丢弃它并使用其创建会话 cookie 的默认值。