在做 FreeCodeCamp 的一個(gè)練習(xí),題目要求能夠接收用戶輸入的時(shí)間參數(shù)杖剪,返回一個(gè) json 文件冻押,包括 unix 時(shí)間戳和自然語(yǔ)言的表示。
使用示例:
https://timestamp-ms.herokuapp.com/December%2015,%202015
https://timestamp-ms.herokuapp.com/1450137600
輸出示例:
{ "unix": 1450137600, "natural": "December 15, 2015" }
查詢 Date 函數(shù)發(fā)現(xiàn)構(gòu)造函數(shù)既可以接收時(shí)間戳為參數(shù)盛嘿,也可以接收自然語(yǔ)言的字符串洛巢。
> 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)
然而他們得到的時(shí)間卻相差了8個(gè)小時(shí),查了下次兆,在 Date.parse
的文檔里發(fā)現(xiàn)了這么一段:
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.
如果輸入的是字符串作為構(gòu)造函數(shù)稿茉,且沒(méi)有指定時(shí)區(qū)的話恨豁,會(huì)默認(rèn)用當(dāng)?shù)貢r(shí)區(qū)忘衍,而 JavaScript 并沒(méi)有提供指定時(shí)區(qū)的方法调榄,于是只能曲線救國(guó)趟咆,先轉(zhuǎn)成時(shí)間戳,把偏差的時(shí)間加上渺蒿,再轉(zhuǎn)回 Date 對(duì)象痢士。
> 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)