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));
}
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));
}
I tried changing nday
to nday=14
but nothing.
Then I tried expire.setTime(today.getTime() + 3600000 * 24 * 14)
,
still nothing
I just need to use this code to get the cookie to expire after a set number of days. Sorry i am new to javascript just started this week.
Share Improve this question edited Sep 10, 2015 at 9:40 Alex Char 33.2k9 gold badges50 silver badges71 bronze badges asked Sep 10, 2015 at 9:22 Quinnystar27Quinnystar27 4222 gold badges5 silver badges15 bronze badges3 Answers
Reset to default 12If you always want to set your cookies for 14 days, delete your nDays parameter and set 14 days directly in the expire.setTime method
function setcookie(cookieName,cookieValue) {
var today = new Date();
var expire = new Date();
expire.setTime(today.getTime() + 3600000*24*14);
document.cookie = cookieName+"="+encodeURI(cookieValue) + ";expires="+expire.toGMTString();
}
If you don't want to use milliseconds you can also use this function:
function AddDays (days) {
var today = new Date();
var resultDate = new Date(today);
resultDate.setDate(today.getDate()+days);
return resultDate;
}
For the lazy:
document.cookie = "your_cookie_name=your_cookie_value; max-age=1209600; path=/";