JavaScript Date.parse里的坑

在做 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)

你可能感兴趣的:(JavaScript Date.parse里的坑)