首页 > 解决方案 > javascript Date.toISOString() 返回差异日期值

问题描述

我对 javascript Date.toISOString() 函数感到困惑,如下例所示,ISO 格式的 x 的日期值如何变为 1 月?

const date = new Date();
const x = (new Date(date.getFullYear(), date.getMonth() , 1));

console.log(date); \\Tue Feb 04 2020 11:11:12 GMT+0800 (Malaysia Time)
console.log(x); \\Sat Feb 01 2020 00:00:00 GMT+0800 (Malaysia Time)

console.log(date.toISOString()); \\2020-02-04T03:11:12.330Z
console.log(x.toISOString()); \\2020-01-31T16:00:00.000Z

标签: javascriptdatetoisostring

解决方案


这是由于从 GMT+08 到 UTC 的时区转换。toISOString函数将日期转换为 UTC(作为注释,您可以通过字符串末尾的“Z”确定日期在 UTC 时区中)。

转换Feb 01 2020 00:00:00 GMT+0800为 ISO 字符串时,日期减少 8 小时,因此变为Jan 31 2020 16:00:00.


推荐阅读