0

代码:

var x = new Date(Date.UTC(0, 0, 0));
x.setUTCFullYear(0);

// in Firefox, writes "Date {Sat Dec 30 0000 16:00:00 GMT-0800 (Pacific Standard Time)}"
// in IE, writes "LOG: Sat Dec 30 16:00:00 PST 1 B.C."
console.log(x);  

// Create a copy of x
var y = new Date(x);

// in Firefox, writes "Date {Sat Dec 30 0000 16:00:00 GMT-0800 (Pacific Standard Time)}"
// in IE, writes "LOG: Invalid Date"

console.log(y);

这似乎发生在任何非常古老的日期

我的问题:这里到底什么是无效的,为什么只有 IE?我怎样才能解决这个问题并实际创建日期的副本?

4

1 回答 1

6

It seems that when a date object is passed to the Date constructor in IE, it's evaluated as something other than the time value (probably calls toString).

To force it to evaluate to the time value, you can do:

new Date(x.getTime());

or

new Date(+x);

or any expression that makes the date return its time value rather than a string.

When a single value is passed to the Date constructor, it's converted to a primitive. The specification doesn't say whether it should be converted to a string or number. So IE isn't non–compliant, it's just behaving differently.

It is unusual though that IE doesn't seem to correctly parse it's own string representation of a date in this case. It seems to fail for any date before 70-01-01, which may be moot since the Gregorian calendar was only introduced in 1582. The time value itself can cover dates from 283458 BC to 287396 AD.

Anyway, the fix is simple.

Edit 2016

In ES5, passing a Date to the Date constructor called Date.prototype.toString so the constructor then had to parse it's own string version of the date. ECMAScript 2015 fixed that so the time value is used directly instead.

However, not all browsers support ECMAScript 2015 yet so even though the chance of new Date(date) returning an incorrect value are small and becoming smaller by the day, it's still safer to use +date (until IE 8 is completely gone).

于 2013-04-17T22:49:10.153 回答