6

First, does JavaScript have no basic Date comparision the way Python might?

In my Node.js script, I have the following lines:

console.log(Date(2012,11,10) < Date(2012, 11, 9))
console.log(Date(2012,11,10) > Date(2012, 11, 9))

However, both of these lines return false.

It appears there are tons of questions about "Date Comparison in JavaScript".

However, for virtually all of them someone responds with their home-made solution for comparing dates, some of them quite long and/or "hacky".

Is there really no inherent or idiomatic way to simply compare dates in JavaScript.
Do any Node libraries support it?

2 Answers 2

12

You need to use the new keyword

console.log(new Date(2012,11,10) < new Date(2012, 11, 9))
console.log(new Date(2012,11,10) > new Date(2012, 11, 9))

As Elias Van Ootegem pointed out it's a standard to return a string if the new keyword is omitted:

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.

Source: 15.9.2 The Date Constructor Called as a Function

3
  • 4
    not just Chrome 22, it's the language standard to return a string when the new keyword is omitted Nov 5, 2012 at 15:17
  • 1
    @chrisco Use var before = new Date(...). If you don't it will assign a string to before and not an date object. Feb 4, 2016 at 0:27
  • But when I do this new Date(2012,11,10) === new Date(2012,11,10) I get false Jan 25, 2020 at 16:22
3

I just ran into date comparison problem myself, and though I can see @dev-null's answer does work for dates constructed as new Date(2012,11,10), it doesn't seem work for parsed dates, at least in my case:

[vps@palladin]~$ node -v
v4.3.2
[vps@palladin]~$ node
> new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)') == new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)')
false
> new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)') < new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)')
false
> new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)') > new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)')
false

The only way that I found to reliably compare J/S Date objects is using getTime() function, and compare the results from both.

> new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)').getTime() == new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)').getTime()
true
> new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)').getTime() < new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)').getTime()
false
> new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)').getTime() > new Date('Wed Mar 09 2016 17:31:58 GMT-0800 (PST)').getTime()
false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.