JS时间转换的一个坑位

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

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

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

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

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

> 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().
posted @ 2018-05-30 16:55  e.e.p  阅读(397)  评论(0编辑  收藏  举报