javascript - 夏令时开始时的无效时间

标签 javascript date time dst

简短版本

在 JavaScript 中,new Date(2013, 9, 20) 可以合法返回 10 月 19 日吗?

长版

当夏令时开始时,由于时钟向前调整,本地时间会出现间隙。 如果我构造一个时间在此间隔内的 Date 对象,根据 ECMAScript 规范,预期的行为是什么?

各种浏览器的行为有所不同,如下所示。 (我在 Windows 8 上运行了这些测试。)

示例 1:在太平洋时区 (UTC-08) 中,表达式

new Date(2013, 2, 10, 2, 34, 56).toString() // Sun Mar 10 2013 02:34:56

给出以下结果:

IE 10:      Sun Mar 10 03:34:56 PDT 2013
IE 11:      Sun Mar 10 2013 03:34:56 GMT-0700 (Pacific Daylight Time)
Chrome 29:  Sun Mar 10 2013 01:34:56 GMT-0800 (Pacific Standard Time)
Firefox 23: Sun Mar 10 2013 03:34:56 GMT-0700 (Pacific Standard Time)

示例 2:在巴西利亚时区 (UTC-03),表达式

new Date(2013, 9, 20, 0, 34, 56).toString() // Sun Oct 20 2013 00:34:56

给出以下结果:

IE 10:      Sun Oct 20 01:34:56 UTC-0200 2013
IE 11:      Sun Oct 20 2013 01:34:56 GMT-0200 (E. South America Daylight Time)
Chrome 29:  Sat Oct 19 2013 23:34:56 GMT-0300 (E. South America Standard Time)
Firefox 23: Sat Oct 19 2013 23:34:56 GMT-0300

从这两个例子看来,IE是向前调整时间,Chrome是向后调整时间,而Firefox拿不定主意。

规范内容:根据我收集到的信息,new Date(yyyy, mm-1, dd, hh, mi, ss) 构造了一个 日期,时间值为 UTC(yyyy-mm-dd hh:mi:ss),其中

UTC(t) = t – LocalTZA – DaylightSavingTA(t – LocalTZA)

LocalTZA 是标准时间的本地时区调整(例如太平洋时区的 -08:00),DaylightSavingTA(t) 是 t 的夏令时调整(例如 DST 期间为 01:00,其他时间为 00:00)。

不过,我不清楚对于太平洋时区的 t = 2013-03-10 10:34:56 或 t 参数,DaylightSavingTA 应该返回什么> = 巴西利亚时区 2013-10-20 03:34:56。

最佳答案

what is the expected behavior according to the ECMAScript specification?

好问题!您是正确的,这取决于严格未定义的 DaylightSavingTA,但是我们可以从它在反函数中使用时的工作方式得出有关 DaylightSavingTA 的含义:

LocalTime(t) = t + LocalTZA + DaylightSavingTA(t)

为了将 UTC t 正确转换为本地时间,DaylightSavingTA(hour_at_beginning_of_dst) 必须为 1 小时,DaylightSavingTA(hour_after_end_of_dst) 必须为 0。

在 UTC() 函数中使用表示 DST 调整时间的 t 调用相同的函数。因此,在 DST 开始时不存在的本地时间中,夏令时 TA(提前一小时的夏令时调整时间)为 1 小时。因此:

Can new Date(2013, 9, 20) legitimately return October 19?

是的。

I'm asking because I (and probably others) have written code like new Date(year, month, day) to construct a date without a time, and evidently this doesn't always work!

确实!使用 UTC 日期进行此类计算 - new Date(Date.UTC(2013, 9, 20))getUTC* 方法。一般来说,除了最终面向用户的时间呈现之外,最好坚持使用 UTC。

关于javascript - 夏令时开始时的无效时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897658/

相关文章:

javascript - Framer Motion - 过时的自定义值 - 更改自定义值不会触发更新

javascript - 如何删除输入字段中文本前的一个或多个空格

javascript - 在 Angular 中编写可链接函数的正确方法是什么?

php - 如何使用 PHP 获取时间值(与 Excel 中的 TIMEVALUE() 函数相同)

相对于文件的 Javascript 路径

date - 如何将带有时间(日期)类型的文件加载到 Hive 表中?

java - Jackson OffsetDateTime 序列化 Z 而不是 +00 :00 timezone?

python - 在 Pandas 中读取具有历史日期的 CSV 文件

java - 以这种格式显示 Java 8 Time api "HH:mma"(05 :53PM) and add set Time with only minutes

c++ - 处理夏令时 - C++