如何在 Javascript 中将 cookie 设置为在 1 小时内过期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3794989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:11:59  来源:igfitidea点击:

How to set a cookie to expire in 1 hour in Javascript?

javascript

提问by Dave

How to set this cookie to expire in one hour from the current time:

如何将此 cookie 设置为从当前时间起一小时后过期:

document.cookie = 'username=' + value; + 'expires=' + WHAT GOES HERE?; + 'path = /';

回答by Darin Dimitrov

Code :

代码 :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

回答by Salvador Dali

You can write this in a more compact way:

您可以以更紧凑的方式编写此代码:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

对于像我这样浪费一个小时试图弄清楚为什么没有在 Chrome 中设置过期 cookie(但可以设置没有过期)的人来说,这里是答案:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

出于某种奇怪的原因,Chrome 团队决定忽略来自本地页面的 cookie。因此,如果您在本地主机上执行此操作,您将无法在 Chrome 中看到您的 cookie。因此,要么将其上传到服务器上,要么使用其他浏览器。