在Javascript中:为什么新日期('2012-1-15') - 新日期('2012-01-15')== 21600000 [英] In Javascript: Why new Date('2012-1-15') - new Date('2012-01-15') == 21600000
问题描述
我很困惑但是在javascript中:
I'm confused but in javascript:
> new Date('2012-1-15') - new Date('2012-01-15')
21600000
为什么? (21600000/1000/3600 == 6小时)
Why is that? (21600000 / 1000 / 3600 == 6 hours)
推荐答案
日期格式 yyyy-mm-dd
(2012-01-15)被解析为UTC日期,而 yyyy-m-dd
(2012-1-15)被解析为当地的约会。如果您在每个上使用 .toString
,则会显示此信息。
The date format yyyy-mm-dd
(2012-01-15) is parsed as being a UTC date while yyyy-m-dd
(2012-1-15) is parsed as a local date. This is shown if you use .toString
on each.
> (new Date( '2012-01-15' )).toString()
"Sat Jan 14 2012 16:00:00 GMT-0800 (Pacific Standard Time)"
> (new Date( '2012-1-15' )).toString()
"Sun Jan 15 2012 00:00:00 GMT-0800 (Pacific Standard Time)"
请注意,我在加利福尼亚,因此是太平洋标准时间。如果您在不同的时区,您将得到不同的结果。
Note that I am in California, hence the Pacific Standard Time. If you are in a different time zone you will get different results.
当JavaScript分析日期时,它会先尝试在更多区域(例如UTC)中使用的格式,然后再尝试本地化日期格式。 UTC日期格式的最后一部分是GMT的时区偏移量,当它丢失时假设为0(如本例所示)。要获得相同的日期,您需要完整的UTC时间戳:2012-01-15T00:00:00-08:00。
When JavaScript parses dates it tries formats used in more areas (such as UTC) first before it tries localized date formats. The last part of the UTC date format is a timezone offset from GMT which is assumed to be 0 when it is missing (as it is in this example). To get the same date you would need the full UTC timestamp: 2012-01-15T00:00:00-08:00.
这篇关于在Javascript中:为什么新日期('2012-1-15') - 新日期('2012-01-15')== 21600000的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!