gpt4 book ai didi

javascript - 类似的日期格式产生意外的日期 Javascript

转载 作者:数据小太阳 更新时间:2023-10-29 04:19:01 26 4
gpt4 key购买 nike

为什么第一个输入可以正常工作,但第二个输入却给我 5 小时前的结果?

new Date("2000-1-1")
Sat Jan 01 2000 00:00:00 GMT-0500 (EST)
new Date("2000-01-01")
Fri Dec 31 1999 19:00:00 GMT-0500 (EST)

如何才能让第二个与我合作?

var a = new Date("2000-1-1"); // Sat Jan 01 2000 00:00:00 GMT-0500 (EST)
var b = new Date("2000-01-01"); // Fri Dec 31 1999 19:00:00 GMT-0500 (EST)
console.log(a, a.getTime());
console.log(b, b.getTime());

最佳答案

您看到这个的原因实际上在 MDNDate.parse() 页面上有描述。 (其中描述了有关官方支持的 Date 参数格式的许多细节)。具体来说:

Differences in assumed time zone

Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore Date objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.

所以您看到的是两件事的结合:

  1. 构造函数正在读取格式正确的 ISO 日期值作为 UTC,因为没有提供时区,并且
  2. 准确识别您本地计算机时区为美国东部时区,并适当调整该值。

因此,您看到的是 UTC 时间 2000 年 1 月 1 日午夜(或 1999 年 12 月 31 日晚上 7 点)的美国东部时区版本。

由于您的第一个示例使用的是非标准格式(从 JS 的 Angular 来看),因此第一个假设没有发挥作用,并且假设该值的本地时区(特定于浏览器的时区)决定如何处理非标准格式)。

关于javascript - 类似的日期格式产生意外的日期 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43522427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com