简体   繁体   English

JavaScript日期对象因格式而异:yyyy-mm-dd与mm-dd-yyyy

[英]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.

相关问题 在JavaScript中将日期格式从mm-dd-yyyy转换为yyyy-mm-dd - Convert Date format from mm-dd-yyyy to yyyy-mm-dd in javascript 格式 JavaScript 日期为 yyyy-mm-dd - Format JavaScript date as yyyy-mm-dd 在JavaScript中将mm-dd-yyyy转换为日期 - Convert mm-dd-yyyy to date in javascript u"'' 值的日期格式无效。它必须是 YYYY-MM-DD 格式,我需要它是 MM-DD-YYYY - u"'' value has an invalid date format. It must be in YYYY-MM-DD format i need it to be MM-DD-YYYY 将“ yyyy-mm-dd”日期格式设置为“ dd month yyyy” - Format a “yyyy-mm-dd” date into “dd month yyyy” 如何将NgbDatePicker格式从YYYY-MM-DD更改为MM-DD-YYYY角4? - how to change NgbDatePicker format from YYYY-MM-DD to MM-DD-YYYY angular 4? 使用JavaScript在pentaho中将日期格式从“ yyyy-mm-dd”转换为“ dd / mm / yyyy” - Date format conversion from “yyyy-mm-dd” to “dd/mm/yyyy” in pentaho using javascript 在Javascript中将yyyy-mm-dd转换为其他日期格式 - Convert a yyyy-mm-dd to other date format in Javascript Javascript将字符串转换为日期格式yyyy-MM-dd - Javascript convert string to date format yyyy-MM-dd 在 javascript 中将日期转换为有线格式 (YYYY-MM-DD) - Transform date to wire format (YYYY-MM-DD) in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM