设置Cookie会在2小时后过期

Tur*_*min 7 javascript cookies

我有这个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=/";
}
Run Code Online (Sandbox Code Playgroud)

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

Séb*_*ien 9

如果要使用相同类型的函数,请将daysparam转换为hourspass并传递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=/";
}
Run Code Online (Sandbox Code Playgroud)


OBV*_*OBV 5

试试这个:

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;
};
Run Code Online (Sandbox Code Playgroud)

用法:

<script>
writeCookie ("myCookie", "12345", 24);
</script>
//for 24 hours
Run Code Online (Sandbox Code Playgroud)


小智 5

最明显的事情是让"过期"日期+2小时?:).在这里你有一个很好的原型: 为Javascript Date对象增加小时数?