How to make this cookie expire after 14 days

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

}
Run codeHide result

I tried to change ndayto nday=14, but nothing.

Then I tried expire.setTime(today.getTime() + 3600000 * 24 * 14), nothing else

I just need to use this code so that the cookie expires after a certain number of days. Sorry I'm new to javascript just started this week.

+4
source share
2 answers

If you always want to set your cookies within 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+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
+5
source

If you do not 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;
}
+1
source

Source: https://habr.com/ru/post/1606738/


All Articles