设置cookie在3小时后过期

时间:2015-07-02 12:22:57

标签: javascript cookies

将Cookie设置为3小时后过期

我有这个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=/";
}

如何让Cookie在3小时后过期?

3 个答案:

答案 0 :(得分:0)

第一种方法

修改功能为:

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

您将使用createCookie(...,...,3);

第二种方法

或使用以下原型:

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

以下createCookie函数:

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

您将使用createCookie(...,...,new Date().addHours(3));

答案 1 :(得分:0)

您的代码似乎只保存了一天中的1/12。

days*2*60*60*1000

应该是

days*24*60*60*1000

因此,当您需要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);

答案 2 :(得分:0)

希望它应该像这样

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