2015-09-10 48 views
4

如何獲得這個cookie到後14天

function setcookie(cookieName, cookieValue, nDays) { 
 
    var today = new Date(); 
 
    var expire = new Date(); 
 
    if (nDays == null || nDays == 0) nDays = 1; 
 
    expire.setTime(today.getTime() + 3600000 * 24 * nDays); // changed that to * 14 
 
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString(); 
 
} 
 

 
function readcookie(cookieName) { 
 
    var theCookie = " " + document.cookie; 
 
    var ind = theCookie.indexOf(" " + cookieName + "="); 
 
    if (ind == -1) ind = theCookie.indexOf(";" + cookieName + "="); 
 
    if (ind == -1 || cookieName == "") return ""; 
 
    var ind1 = theCookie.indexOf(";", ind + 1); 
 
    if (ind1 == -1) ind1 = theCookie.length; 
 
    return unescape(theCookie.substring(ind + cookieName.length + 2, ind1)); 
 

 
}

我試圖改變ndaynday=14但沒有到期。

然後我試圖expire.setTime(today.getTime() + 3600000 * 24 * 14), 仍然沒有

我只需要使用此代碼來獲取cookie的天集數後過期。對不起,我是新來的JavaScript剛剛開始這個星期。

回答

5

如果你總是要設置你的cookies 14天,刪除nDays參數,並在expire.setTime方法

function setcookie(cookieName,cookieValue) { 
    var today = new Date(); 
    var expire = new Date(); 
    expire.setTime(today.getTime() + 3600000*24*14); 
    document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString(); 
} 
+0

感謝。我會試試看。我能問,雖然怎麼來的,當我改變nDays = 14;它不起作用。我以爲它會做360000個* 24個* nDays這將有14 – Quinnystar27

+0

刪除「如果(nDays == NULL || nDays == 0)」行,這將是確定 –

1

直接設置14天如果你不想使用毫秒你也可以使用此功能:

function AddDays (days) { 
    var today = new Date(); 
    var resultDate = new Date(today); 
    resultDate.setDate(today.getDate()+days); 
    return resultDate; 
}