Javascript: new Date() 用特定的日期字符串初始化 returns 不同时区的两个不同日期
Javascript: new Date() initialized with specific date string returns two different dates in different timezones
我正在使用 new Date() 为特定日期创建日期对象。但它 returns 两个不同时区的不同日期。见下文:
当我的机器处于印度时区 (IST) 时
console.log(new Date('2020-08-28')); //returns Fri Aug 28 2020 05:30:00 GMT+0530 (India Standard Time)
当我的机器处于美国时区 (CST) 时
console.log(new Date('2020-08-28')); //returns Fri Aug 27 2020 19:00:00 GMT-0500 (Central Daylight Time)
即使我告诉 JS 为给定字符串创建日期,这怎么会发生?这里的字符串是'2020-08-28'。
为什么会发生这种情况以及如何在这种情况下忽略时区?
当您通过传递字符串实例化 Date
时,它应该是指定时区的完整 ISO 8601 字符串。由于您没有指定,它需要格林威治标准时间 (±00:00),然后在显示时使用您当地的时区。如果要将日期显示为 GMT,请使用此选项:
console.log(new Date('2020-08-28').toUTCString());
From the ECMAScript specification:
When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
表格本身在 Date Time String Format 中进行了描述。
请务必注意,将 date-only 格式视为 UTC 与将此类格式视为本地时间的 ISO 8601 规范相冲突。这是一个已知问题,was done deliberately 以“网络现实”的名义。
我正在使用 new Date() 为特定日期创建日期对象。但它 returns 两个不同时区的不同日期。见下文:
当我的机器处于印度时区 (IST) 时
console.log(new Date('2020-08-28')); //returns Fri Aug 28 2020 05:30:00 GMT+0530 (India Standard Time)
当我的机器处于美国时区 (CST) 时
console.log(new Date('2020-08-28')); //returns Fri Aug 27 2020 19:00:00 GMT-0500 (Central Daylight Time)
即使我告诉 JS 为给定字符串创建日期,这怎么会发生?这里的字符串是'2020-08-28'。
为什么会发生这种情况以及如何在这种情况下忽略时区?
当您通过传递字符串实例化 Date
时,它应该是指定时区的完整 ISO 8601 字符串。由于您没有指定,它需要格林威治标准时间 (±00:00),然后在显示时使用您当地的时区。如果要将日期显示为 GMT,请使用此选项:
console.log(new Date('2020-08-28').toUTCString());
From the ECMAScript specification:
When the UTC offset representation is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.
表格本身在 Date Time String Format 中进行了描述。
请务必注意,将 date-only 格式视为 UTC 与将此类格式视为本地时间的 ISO 8601 规范相冲突。这是一个已知问题,was done deliberately 以“网络现实”的名义。