简体   繁体   English

设置 cookie 在 3 小时后过期

[英]Set a cookie expire after 3 hours

Set a cookie expire after 3 hours设置 cookie 在 3 小时后过期

I have this JavaScript code:我有这个 JavaScript 代码:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*2*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 3 hours?如何让 cookie 在 3 小时后过期?

1st Method第一种方法

Modify function to be:修改函数为:

function 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=/";}

And you will use createCookie(...,...,3);您将使用createCookie(...,...,3);

2nd Method方法二

Or using the following prototype:或者使用以下原型:

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

And the following createCookie function:以及以下 createCookie 函数:

  function createCookie(name,value,date) {
        if(date){
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";}

And you will use createCookie(...,...,new Date().addHours(3));您将使用createCookie(...,...,new Date().addHours(3));

Your code seems to save the cookie for only 1/12 of a day.您的代码似乎只将 cookie 保存了一天的 1/12。

days*2*60*60*1000

should be应该

days*24*60*60*1000

So when you want 3 hours you need to save the cookie for 1/8 of a day 24/8因此,当您需要 3 小时时,您需要将 cookie 保存 1/8 天24/8

function 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=/";
}

createCookie("name", "3 hours", 1/8);

Hope it should be like this希望它应该是这样的

function 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=/";}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM