JS时间转换的一个坑位

在作项目的时候,无心发现了一个小东西。 new Date('2018-05-15') new Date('2018-5-15')ide

输出的结果是不一样的,相差了8小时。而后让我回忆到以前看的一个时间转换函数,把-替换成/。因而,我把它替换了一下。问题就解决了,返回的就是相同的时间。因此能够简单地得出一个结论:函数

  1. 其实不关是否加了0的问题
  2. 把-替换成/,能够躲过这个坑

原本这个日记已经完结,我没死心又跑去MDN找了Date对象的知识。其中有一个写着new Date(dateString),接着,咱们看到:该字符串(dateString)应该能被 Date.parse() 方法识别。再翻到这个parse的文档,里面就写着相似(2015-02-31)这种属于非法的格式。这也就正式完结了,这是一个超级基础的知识啊。ui

接着还有后续,热心网友提供了一个其余信息this

> new Date("2012/03/13")
Tue Mar 13 2012 00:00:00 GMT-0400 (EDT)
This parses to midnight in the local time zone. This behavior is universal across browsers.

> new Date("2012-03-13")
Mon Mar 12 2012 20:00:00 GMT-0400 (EDT)
This can be interpreted as an ISO-8601 date, and so it is (following our last rule of thumb). This means that it is parsed as UTC. But it is displayed using local time. I'm in the EDT time zone, hence the difference of four hours. This format is only supported by newer browsers (Chrome, FF4+, IE9).

> new Date("2012-3-13")
Tue Mar 13 2012 00:00:00 GMT-0400 (EDT)
This cannot be interpreted as an ISO-8601 date, since it's missing a "0" in front of the month ("3" vs. "03"). So Chrome falls back to interpreting this as a local time. At the moment, Chrome is the only browser which supports this particular gem of a format.

A final cautionary note: if you are writing a library and wish to convert date strings to millis since epoch, the built-in Date.parse method looks like just the ticket. But you'll eventually run into an issue. For reasons known only to its authors, MooTools overrides this function with an incompatible version (theirs returns a Date, not a number). What you really want is new Date(dateString).getTime().
相关文章
相关标签/搜索