[英]Javascript Date object different depending on format: yyyy-mm-dd vs mm-dd-yyyy
Another JavaScript Date conundrum... 另一个JavaScript日期难题...
I get two completely different Date objects depending on the format I pass to the Date constructor (Date.parse() also produces different results). 根据传递给Date构造函数的格式,我得到了两个完全不同的Date对象(Date.parse()也产生不同的结果)。
Example:
例:
new Date('04-27-2016');
新日期('04 -27-2016'); => Wed Apr 27 2016 00:00:00 GMT-0500 (Central Daylight Time)
=> 2016年4月27日,星期三00:00:00 GMT-0500(中央夏令时)
Date.parse('04-27-2016');
Date.parse('04 -27-2016' ); => 1461733200000
=> 1461733200000
vs VS
new Date('2016-04-27');
新日期('2016-04-27'); Apr 26 2016 19:00:00 GMT-0500 (Central Daylight Time)
2016年4月26日19:00:00 GMT-0500(中央夏令时)
Date.parse('04-27-2016');
Date.parse('04 -27-2016' ); => 1461715200000
=> 1461715200000
I can easily work around this situation in my code, but I would like an explanation as to why/how this is doing what it does. 我可以在代码中轻松解决这种情况,但是我想解释一下为什么/如何做它所做的事情。
The ISO format you use in the second example has UTC as its default timezone. 在第二个示例中使用的ISO格式将UTC作为其默认时区。 It's described here on MDN .
在MDN上对此进行了描述。 If you want the correct behaviour for this format, you have to add the information about timezone:
new Date('2016-04-27 GMT-0500');
如果您想要此格式的正确行为,则必须添加有关时区的信息:
new Date('2016-04-27 GMT-0500');
or you have to also specify the time: new Date('2016-04-27 00:00:00');
或者您还必须指定时间:
new Date('2016-04-27 00:00:00');
In my opinion it's better not to use the built-in parser and use some library instead. 我认为最好不要使用内置的解析器,而应使用一些库。 For example Moment.js is great.
例如Moment.js很棒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.