2015-07-02 64 views
-2

設置3小時設置cookie到期後3小時

我有這樣的JavaScript代碼後,一個cookie過期:

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

我怎樣才能讓在3小時後該cookie過期嗎?

+0

該代碼是誤導...該餅乾喔ld過期'days * 2 hours' - 因此,調用像'createCookie(「blah」,「fred」,1.5)這樣的函數可以做到這一點 –

+0

把'days * 2 * 60 * 60 * 1000'改爲'days * 24 * 60 * 60 * 1000',然後調用函數createCookie('name','value',0.125)。 – Marvin

+0

[Set a cookie expire after 2 hours]可能的重複(http://stackoverflow.com/questions/19068812/set-a-cookie-expire-after-2-hours) –

回答

0

第1種方法

修改功能是:

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);

第2種方法

或者使用下面的原型:

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));

0

你的代碼似乎保存的Cookie只開了一天的1/12。

days*2*60*60*1000 

應該

days*24*60*60*1000 

所以,當你想3小時您需要保存cookie的一天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); 
0

希望它應該是這樣的

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