最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get this cookie to expire after 14 days - Stack Overflow

programmeradmin8浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 12

If 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=/";
发布评论

评论列表(0)

  1. 暂无评论