任何人都可以用破折号分隔的日期解释以下行为吗?
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
最佳答案
这看起来很奇怪,因为某些日期被解释为部分 ISO 日期(带有破折号的日期),并且它们被解释为 UTC,而其他日期则被神奇地解析并被解释为本地时区。
这就是为什么我总是建议使用 Moment对于日期解析,始终明确提供您期望的格式,并始终使用 true
作为 moment()
的第三个参数进行严格验证,以避免任何可能的误解,因为将错误的数据放入数据库比崩溃更糟糕,而且日期在很多地方都至关重要。
示例:
console.log( moment('2015/03/03', 'YYYY/MM/DD', true).toISOString() );
2015-03-02T23:00:00.000Z
console.log( moment('2015-03-03', 'YYYY-MM-DD', true).toISOString() );
2015-03-02T23:00:00.000Z
console.log( moment('2015/04/03', 'YYYY/MM/DD', true).toISOString() );
2015-04-02T22:00:00.000Z
console.log( moment('2015-04-03', 'YYYY-MM-DD', true).toISOString() );
2015-04-02T22:00:00.000Z
如您所见,这并不奇怪。
有关如何以及为什么验证日期的更多信息,请参阅此答案:
关于javascript - Javascript 上的有趣怪癖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42653162/