2011-09-23 69 views
2

以下是告诉用户上次访问页面的脚本+ HTML。toDateString有什么问题

<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> 

在上面的脚本中设置cookie的语句是:document.cookie = "lastVisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();。如果在此我用now.toDateString()替换now.toGMTString()在浏览器中的过期时间是“当我关闭浏览器时失效”。这是为什么 ? 可以用toGMTString。预计截止日期为2012年3月。

+0

为什么要使用“toDateString()”而不是“toGMTString()”?或者你只是好奇为什么事情是这样的? – Pointy

+0

@ Pointy _curious_ –

+0

.toDateStr趋向于以不同于.toGMTString的格式输出。最有可能的是,无论您的浏览器输出什么内容,都无法将其作为cookie使用的适当日期进行整合,因此只需将其解释为0即可。 –

回答

4

如果您在控制台都去尝试一下,你会发现他们不给同样的结果字符串都:当你设置一个cookie you have to specify the time using GMT format,如果你不知道你的浏览器

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

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

未能确认到期时间并认为没有指定。 When no expiry date is specified, cookie are created as "session cookie",一旦会话结束就会过期(例如关闭浏览器)。

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

+1

acc上测试过[回答这里](http://stackoverflow.com/questions/7529307/unable-to-display-the-last-visited-date/7529840#7529840)_toGMTString已弃用_。如果是这样,那么替代品是什么? –

+0

[toUTCString()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toUTCString)是为了取代它。它基本上是一样的,只是更好。正如[UTC维基百科页面](http://en.wikipedia.org/wiki/Coordinated_Universal_Time)所述; “UTC在概念上与通用时间和格林威治标准时间(GMT)不同,但它可以在不需要亚秒精度的情况下互换使用。”由于cookie的到期时间是第二次,因此显然不需要亚秒精度。 – Lepidosteus

1

这是由于从toDateString()输出的格式不适用于指定cookie的到期日期。 * toDateString() - Fri Sep 23 2011 * toGMTString() - Fri, 23 Sep 2011 16:31:24 GMT

由于不被认可的cookie将使用默认行为,并在会议结束时届满的日期字符串。

0

toDateString不会生成有效的日期 - 没有时区,也没有包含时间数据。 toGMT string返回一个明确的时间。

我总是希望得到一个整数时间戳,但javascript时间戳是毫秒 - 比'unix'秒格式大一千倍。

总是有max-age