在作項目的時候,無心發現了一個小東西。 new Date('2018-05-15')
new Date('2018-5-15')
ide
輸出的結果是不一樣的,相差了8小時。而後讓我回憶到以前看的一個時間轉換函數,把-替換成/。因而,我把它替換了一下。問題就解決了,返回的就是相同的時間。因此能夠簡單地得出一個結論:函數
- 其實不關是否加了0的問題
- 把-替換成/,能夠躲過這個坑
原本這個日記已經完結,我沒死心又跑去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().