我使用 jquery 设置 cookie。 但 consoleLog 日期和过期日期不同。
function setCookie() {
const date = new Date(); //Tue Oct 22 2019 17:45:53 GMT+0900 (한국 표준시)
const expires = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59); // Tue Oct 22 2019 23:59:59 GMT+0900 (한국 표준시)
$.cookie('AAA', '', { expires });
}
但是过期日期是 2019-10-22T14:59:59.000Z 时间不一样。 我在 Chrome 中发现了这个问题。 非常感谢您的帮助!
最佳答案
简单的回答
当您将非 UTC 日期放入过期日期时,javascript 会自动将该日期转换为 GMT。
JavaScript Cookie expires time must be GMT/UTC
您可以使用以下命令获得一个以 23:59:59 结束的 UTC 日期
const date = new Date();
const expires = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59));
console.log(expires.toUTCString());
更新 根据 OP 在评论中要求提供另一种方法,这样他就不需要使用 getFullYear
、getMonth
等方法。以下是如何在不使用 Date.UTC
和年/月函数的情况下将 currentDate 转换为结束于 23:59:59 的 UTC:
var curDate = new Date();
curDate.setUTCHours(23);
curDate.setUTCMinutes(59);
curDate.setUTCSeconds(59);
console.log(curDate.toISOString())
关于javascript - jQuery cookie 过期时间不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58500395/