代码之家  ›  专栏  ›  技术社区  ›  Hamed Minaee

我试图在cookie中保存1小时,但得到的日期无效

  •  0
  • Hamed Minaee  · 技术社区  · 6 年前

    我有一个代币,我想把它存到饼干里只存1个小时。

    这是我的代码:

            time= 3600 * 1000;
        let expires = new Date();
        expires.setDate(expires + time);
        console.log(expires);
        document.cookie =`${name}=${value};expires=${expires.toUTCString()};path=/`;
    

    当我在chrome中运行它时,我看到以下内容:

    Invalid Date
    

    有关更多信息,我使用以下方法实现我的功能:

    How to set a cookie to expire in 1 hour in Javascript?

    有人能解释一下吗?我做错什么了?

    1 回复  |  直到 6 年前
        1
  •  0
  •   sbrass    6 年前

    这是因为 expires+time 部分。你不能在这样的数字上加日期。 你可以试试

    let expires=new Date(new Date().valueOf()+time);