JavaScript Date.parse裡的坑

weixin_34075551發表於2016-01-30

在做 FreeCodeCamp 的一個練習,題目要求能夠接收使用者輸入的時間引數,返回一個 json 檔案,包括 unix 時間戳和自然語言的表示。

使用示例:
https://timestamp-ms.herokuapp.com/December%2015,%202015
https://timestamp-ms.herokuapp.com/1450137600

輸出示例:
{ "unix": 1450137600, "natural": "December 15, 2015" }

查詢 Date 函式發現建構函式既可以接收時間戳為引數,也可以接收自然語言的字串。

> new Date('December 15, 2015')
Tue Dec 15 2015 00:00:00 GMT+0800 (CST)
> new Date(1450137600*1000)
Tue Dec 15 2015 08:00:00 GMT+0800 (CST)

然而他們得到的時間卻相差了8個小時,查了下,在 Date.parse 的文件裡發現了這麼一段:

Given a string representing a time, parse()
returns the time value. It accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g. "Mon, 25 Dec 1995 13:30:00 GMT"
. It understands the continental US time zone abbreviations, but for general use, use a time zone offset, for example, "Mon, 25 Dec 1995 13:30:00 +0430"
(4 hours, 30 minutes east of the Greenwich meridian). If a time zone is not specified and the string is in an ISO format recognized by ES5, UTC is assumed. However, in ECMAScript 2015 ISO format dates without a timezone are treated as local.

如果輸入的是字串作為建構函式,且沒有指定時區的話,會預設用當地時區,而 JavaScript 並沒有提供指定時區的方法,於是只能曲線救國,先轉成時間戳,把偏差的時間加上,再轉回 Date 物件。

> d = new Date('December 15, 2015')
Tue Dec 15 2015 00:00:00 GMT+0800 (CST)
> d1 = new Date(1450137600*1000)
Tue Dec 15 2015 08:00:00 GMT+0800 (CST)
> d = new Date(d.getTime()-1000*60*d.getTimezoneOffset())
Tue Dec 15 2015 08:00:00 GMT+0800 (CST)

相關文章