Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Node.js Date Comparison and Array sort by Date

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?

like image 761
Bill VB Avatar asked Nov 05 '12 15:11

Bill VB


1 Answers

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

like image 128
Andreas Louv Avatar answered Oct 12 '22 23:10

Andreas Louv