thed0ctor
thed0ctor

Reputation: 1396

Why does JavaScript Date constructor fail on this number but works fine as a method

I'm honestly not sure how to phrase this question. Basically open a JavaScript console (node, your browser or wherever) and try this:

Date(564018060878018050) // 'Fri Nov 23 2018 06:22:20 GMT-0800 (Pacific Standard Time)'
new Date(564018060878018050) // <-- Invalid Date

I have no idea why the first one works and the second one doesn't. Is there another way to parse. I'm trying to stay away from using a library for this.

Upvotes: 2

Views: 161

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272026

The specs says that:

The actual range of times supported by ECMAScript Date objects is [...] exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The valid range is much smaller than the value you used (564,018,060,878,018,050).

And deep inside the Date(value) constructor we have:

If abs(time) > 8.64 × 1015, return NaN.

This explains why new Date(564018060878018050) yields invalid date.

As for Date(564018060878018050) the specs say that:

... Invoking a constructor without using new has consequences that depend on the constructor. For example, Date() produces a string representation of the current date and time rather than an object.

So Date(value) is supposed to return current date as a string and not a date.

> Date(564018060878018050) === (new Date()).toString()
< true

> typeof Date(564018060878018050)
< "string"

Upvotes: 5

Thomaz Capra
Thomaz Capra

Reputation: 1053

You are calling the Date constructor as Function and as say in ECMAscript doc:

"When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC)."

"NOTE The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments."

You can find more details here: https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2

Upvotes: 0

Related Questions