Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript toDateString有什么问题_Javascript_Cookies - Fatal编程技术网

Javascript toDateString有什么问题

Javascript toDateString有什么问题,javascript,cookies,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.onloa

下面是一个脚本+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>

曲奇
window.onload=initLastVisit;
函数initlastVisite(){
var now=新日期();
var last=新日期();
now.setMonth(now.getMonth()+6);
document.cookie=“lastVisit=“+last.toDateString()+”;path=/;expires=“+now.togmString();
document.getElementById(“lastVisitedOn”).innerHTML=document.cookie.split(“=”)[1];
}
输入您的姓名
在上述脚本中设置cookie的语句是:
document.cookie=“lastVisit=“+last.toDateString()+”;path=/;expires=“+now.togmstring()。如果在本例中,我将
now.togmString()
替换为
now.toDateString()
,则浏览器中的过期时间为“当我关闭浏览器时过期”。为什么呢?
使用
togmString
可以。到期日期如预期的那样是2012年3月。

如果您在控制台中尝试这两种方法,您将看到它们根本不会给出相同的结果字符串:

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

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

当您设置cookie时,如果您没有浏览器,则无法识别到期时间,并且认为没有指定任何时间。一旦会话结束(如关闭浏览器),它将过期


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

这是由于从
toDateString()
输出的格式对于指定cookie的到期日期无效。 *
toDateString()
-
2011年9月23日星期五
*
togmString()
-
2011年9月23日星期五16:31:24 GMT


由于未识别日期字符串,cookie将使用默认行为,并在会话结束时过期。

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

我一直希望有一个整数时间戳,但javascript时间戳是毫秒——比“unix”秒格式大1000倍


始终存在最大年龄

为什么要使用“toDateString()”而不是“TogmString()”?或者你只是好奇为什么事情是这样的吗?.toDateStr的输出格式与.TogmString不同。最有可能的是,无论您的浏览器输出的是什么,都无法将其视为cookie使用的正确日期,因此只能将其解释为0,即expires-on-close。不推荐使用TogmString的acc。如果是这样的话,更换的是什么?是用来取代它的。这基本上是一样的,只是更好。作为国家;“UTC在概念上与世界时和格林威治标准时间(GMT)不同,但在不需要亚秒精度的情况下可以互换使用。”,因为Cookie的到期时间是以秒为基础的,因此显然不需要亚秒精度。