Javascript上有趣的怪癖

时间:2017-03-07 16:17:29

标签: javascript node.js date timezone

任何人都能用破折号分隔日期来解释以下行为吗?

console.log(new Date('2015/03/03'));
Tue Mar 03 2015 00:00:00 GMT+0000 (GMT Standard Time)

console.log(new Date('2015-03-03'));
Tue Mar 03 2015 00:00:00 GMT+0000 (GMT Standard Time)

console.log(new Date('2015/04/03'));
Fri Apr 03 2015 00:00:00 GMT+0100 (GMT Daylight Time)

console.log(new Date('2015-04-03'));
Fri Apr 03 2015 01:00:00 GMT+0100 (GMT Daylight Time) // This is the weird one

注意:我在英国,冬天GMT + 0,“夏天”GMT + 1。

注意2:我读过我应该使用'/'作为分隔符,特别是因为IE11没有这样做,但我想知道Chrome会怎么样?

注3:在NodeJS中它甚至更奇怪。

console.log(new Date('2015/03/03'));
2015-03-03T00:00:00.000Z

console.log(new Date('2015-03-03'));
2015-03-03T00:00:00.000Z

console.log(new Date('2015/04/03'));
2015-04-02T23:00:00.000Z //This is the weird one this time

console.log(new Date('2015-04-03'));
2015-04-03T00:00:00.000Z

1 个答案:

答案 0 :(得分:3)

这看起来很奇怪,因为有些日期被解释为部分ISO日期(带破折号的日期),它们被解释为UTC,而其他日期被神奇地解析并被解释为本地时区。

这就是为什么我总是建议使用Moment进行日期解析,并始终提供您明确期望的格式,并始终使用true作为{{1的第三个参数严格验证,以避免任何可能的误解,因为将错误的数据放入数据库比崩溃更糟糕,日期在许多地方都很重要。

示例:

moment()

正如你所看到的,这里没有任何惊喜。

有关如何以及为什么验证日期的详细信息,请参阅以下答案: