console.log(new Date(0));
VM655237:1 Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
console.log(new Date("0"));
VM655252:1 Sat Jan 01 2000 00:00:00 GMT+0800 (中国标准时间)
console.log(new Date(0));
VM655237:1 Thu Jan 01 1970 08:00:00 GMT+0800 (中国标准时间)
console.log(new Date("0"));
VM655252:1 Sat Jan 01 2000 00:00:00 GMT+0800 (中国标准时间)
参数是字符串的时候,会使用Date.parse,而其中咋解释字符串 "0" 是实现自己定义的。这与参数是数字的时候完全不同。
The parse function applies the ToString operator to its argument. If ToString results in an abrupt completion the Completion Record is immediately returned. Otherwise, parse interprets the resulting String as a date and time; it returns a Number, the UTC time value corresponding to the date and time. The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the String according to the format described in Date Time String Format (20.3.1.15), including expanded years. If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats. Strings that are unrecognizable or contain out-of-bounds format field values shall cause Date.parse to return NaN.
O__O "…
以下为Mac浏览器测试:
// Chrome
new Date('0')
Sat Jan 01 2000 00:00:00 GMT+0800 (中国标准时间)
// Safari
> new Date('0')
< Sat Jan 01 0000 08:00:00 GMT+0800 (CST)
// Firefox
new Date('0')
Invalid Date
10 回答11.4k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.9k 阅读✓ 已解决
3 回答2.5k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
2 回答2.7k 阅读✓ 已解决
JS里面date语法包含:
new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
四种方式,你这个属于第二种和第三种。
new Date(0)匹配new Date(value);返回自1970年1月1日00:00:00 UTC(the Unix epoch)以来的毫秒数,忽略了闰秒。
new Date('0')匹配new Date(dateString);表示日期的字符串值。该字符串应该能被 Date.parse() 正确方法识别(即符合 IETF-compliant RFC 2822 timestamps 或 version of ISO8601)。
而Date.parse('0')的值为946656000000,所以刚好是2000年。
附:
Date.parse() 方法解析一个表示某个日期的字符串,并返回从1970-1-1 00:00:00 UTC 到该日期对象(该日期对象的UTC时间)的毫秒数,如果该字符串无法识别,或者一些情况下,包含了不合法的日期数值(如:2015-02-31),则返回值为NaN。
由于在解析日期字符串时存在偏差会导致结果不一致,因此推荐始终手动解析日期字符串,特别是不同的ECMAScript实现会把诸如“2015-10-12 12:00:00”的字符串解析为NaN,UTC或者本地时间。
所以mac上有时候会出问题