javascript 设置 cookie 2 小时后过期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19068812/
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-10-27 14:14:35  来源:igfitidea点击:

Set a cookie expire after 2 hours

javascriptcookies

提问by Tureac Cosmin

I have this JavaScript code:

我有这个 JavaScript 代码:

function spu_createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else
        var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

How can I make the cookie expire after 2 hours?

如何让 cookie 在 2 小时后过期?

回答by Sébastien

If you want to use the same type of function, transform the daysparam into hoursand pass 2to get a 2 hour expiration date.

如果要使用相同类型的函数,请将daysparam 转换为hours并传递2以获得 2 小时的到期日期。

function spu_createCookie(name, value, hours)
{
    if (hours)
    {
        var date = new Date();
        date.setTime(date.getTime()+(hours*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else
    {
        var expires = "";
    }

    document.cookie = name+"="+value+expires+"; path=/";
}

回答by OBV

Try this:

试试这个:

function writeCookie (key, value, hours) {
    var date = new Date();

    // Get milliseconds at current time plus number of hours*60 minutes*60 seconds* 1000 milliseconds
    date.setTime(+ date + (hours * 3600000)); //60 * 60 * 1000

    window.document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";

    return value;
};

Usage:

用法:

<script>
writeCookie ("myCookie", "12345", 24);
</script>
//for 24 hours

回答by masahuku

Well -most obvious thing is to make "expire" date +2 hours ? :). Here You have nice prototype for that: Adding hours to Javascript Date object?

嗯 - 最明显的事情是让“过期”日期 +2 小时?:)。在这里,您有很好的原型: 向 Javascript 日期对象添加小时数?

回答by Alex Art.

Try jquery-cookie. Makes it very easy to work with cookies.

试试jquery-cookie。使使用 cookie 变得非常容易。

回答by PMint

This would do it.

这样就可以了。

var now = new Date();
var time = now.getTime();
time += 7200 * 1000;
now.setTime(time);
document.cookie = 
     name+ '=' + value + 
     '; expires=' + now.toGMTString() + 
     '; path=/';