Eason
Eason

Reputation: 13

Strange Date issue for javascript

I try to troubleshot my code and found a strange Date issue for js, I can't understand. On the developer tools of chrome, watch the value of this expression:

new Date(new Date() + (-1)  * 60 * 1000).getTime()

You will got value 'NaN'.

And if watch this:

new Date(new Date() + (-1)  * 60 * 100).getTime()

You will got value '1479095577000'.

Why?

Upvotes: 1

Views: 311

Answers (3)

RobG
RobG

Reputation: 147343

As others have said, the issue is that the first + causes string concatenation rather than addition. You can fix that using Date.now() or:

// Use unary +
console.log(new Date(+new Date() + (-1)  * 60 * 1000).getTime());

// Replacing `+` with `-`
console.log(new Date(new Date() - 1 * 60 * 1000).getTime());

The above may return slightly different results (±2ms or so) due to the performance of the SO console.

Note that whether new Date(new Date() + (-1) * 60 * 1000).getTime()) returns a valid date or not is entirely implementation dependent. Safari returns an invalid date for both expressions in the OP.

Upvotes: 0

Christoph Burschka
Christoph Burschka

Reputation: 4689

The Date object doesn't overload +, so new Date() + n simply concatenates both operands as strings.

Eg:

new Date() + (-1) * 60 * 1000

is equivalent to

String(new Date()) + String((-1) * 60 * 100)

and yields (depending on locale)

Fri Nov 11 2016 09:05:43 GMT+0100-6000

The second example yields a value because the "-6000" looks like a timezone modifier that subtracts sixty hours, even though there is already one. This is a parsing quirk of Chrome - Firefox will reject it, but Chrome will accept the "-6000" and yield a date sixty hours in the future.

This only works if the appended string is exactly four digits (the first two digits for the hours, two for the minutes), and has either a + or a - in front of it. That's why it works if you add "-6000", but not "-60000". It wouldn't work with positive numbers either, unless you added the "+" character manually.

I suspect that what you actually want is

Date.now() - 60 * 1000

Upvotes: 1

arhak
arhak

Reputation: 2542

  • new Date() + (-1) - the date get converted to string, then "-1" is concatenated to it, which is a valid date, because you're subtracting some time zone offset
  • new Date() + (-1) * 60 * 100 = new Date() + (-1 * 60 * 100) = new Date() + (-6000) - which is also a valid date minus some time zone shifting
  • but then a date minus 60000 is not a valid date, due to time zones having only 4 digits top

Upvotes: 2

Related Questions