gpt4 book ai didi

javascript - 不同格式的两个相同日期给出不同的纪元时间

转载 作者:行者123 更新时间:2023-11-30 11:05:51 25 4
gpt4 key购买 nike

下面的语句:

(new Date("1993-09-01")).getTime() == (new Date(1993,9,1)).getTime()  

似乎在 Node、Firefox 和 Chromium 上评估为 false。为什么会这样?

最佳答案

这是因为 JavaScript Date 对象中月份的索引从 0 开始(即一月为 0,二月为 1,依此类推)。

对于右侧的语句,如果当我尝试 console.log( ) 它。

尝试运行下面的代码片段:

const date1 = new Date(1993,9,1);
const date2 = new Date('1993-09-01');

console.log(date1);
console.log(date2);

根据JavaScript Date object documentation , 有多种方法可以实例化日期对象。关于您的问题,您已经使用了文档中提到的两种格式:

1) 新日期(dateString)dateString 的一些可接受格式包括“1995 年 12 月 17 日 03:24:00”、“1995-12-17T03:24:00”和“1993-09-01”。

2) new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

请注意,对于第二个参数 monthIndex,文档指出月份是从 0 开始的,这意味着我们必须从 0 开始计数。

Note: The argument monthIndex is 0-based. This means that January = 0 and December = 11.

因此,new Date(1993, 9, 1) 表示 1993 年 10 月 1 日。您应该使用 new Date(1993, 8, 1) 相反。


即便如此,在进行上述更改后,下面的代码片段仍会打印出错误。为什么会这样?

console.log((new Date('1993-09-01')).getTime() === (new Date(1993,8,1)).getTime())  

再次,我们在 documentation 中引用了这一部分:

If at least two arguments are supplied, missing arguments are either set to 1 (if the day is missing) or 0 for all others.

这意味着在 new Date(1993,8,1) 的情况下,剩余的可选参数(小时、分钟、秒和毫秒)设置为 0。因此,new Date(1993,8,1) 等同于写new Date(1993,8,1,0,0,0,0)

关于javascript - 不同格式的两个相同日期给出不同的纪元时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55648881/

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