【问题标题】:How to get this cookie to expire after 14 days如何让这个 cookie 在 14 天后过期
【发布时间】:2021-09-28 20:56:01
【问题描述】:

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

}

我尝试将 nday 更改为 nday=14 但没有。

然后我尝试了expire.setTime(today.getTime() + 3600000 * 24 * 14), 还是什么都没有

我只需要使用此代码让 cookie 在设定的天数后过期。抱歉,我是本周刚开始接触 javascript 的新手。

【问题讨论】:

    标签: javascript cookies


    【解决方案1】:

    如果你总是想设置 14 天的 cookie,删除你的 nDays 参数,直接在 expire.setTime 方法中设置 14 天

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

    【讨论】:

    • 谢谢。我会试试的。我可以问一下我为什么改变 nDays=14;那没起效。我以为它会做 360000 * 24 * nDays 这本来是 14。
    • 删除“if (nDays == null || nDays == 0)”行就OK了
    • 为什么要先创建日期,然后再修改它?为什么不直接new Date(Date.now() + 1000 * 3600 * 24 * numDays)
    【解决方案2】:

    如果你不想使用毫秒,你也可以使用这个函数:

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

    【讨论】:

      【解决方案3】:

      对于懒人:

      document.cookie = "your_cookie_name=your_cookie_value; max-age=1209600; path=/";
      

      【讨论】:

        猜你喜欢
        • 2019-06-27
        • 2013-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多