JavaScript Date Object Comparison

When comparing date objects in Javascript I found that even comparing the same date does not return true.

 var startDate1 = new Date("02/10/2012");
 var startDate2 = new Date("01/10/2012");
 var startDate3 = new Date("01/10/2012");
 alert(startDate1>startDate2); // true
 alert(startDate2==startDate3); //false

How could I compare the equality of these dates? I am interested in utilizing the native Date object of JS and not any third party libraries since its not appropriate to use a third party JS just to compare the dates.


Solution 1:

That is because in the second case, the actual date objects are compared, and two objects are never equal to each other. Coerce them to number:

 alert( +startDate2 == +startDate3 ); // true

If you want a more explicity conversion to number, use either:

 alert( startDate2.getTime() == startDate3.getTime() ); // true

or

 alert( Number(startDate2) == Number(startDate3) ); // true

Oh, a reference to the spec: §11.9.3 The Abstract Equality Comparison Algorithm which basically says when comparing objects, obj1 == obj2 is true only if they refer to the same object, otherwise the result is false.

Solution 2:

Compare dates using getTime() returning number of milliseconds from epoch (i.e. a number):

var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");
var startDate3 = new Date("01/10/2012");
alert(startDate1.getTime() > startDate2.getTime()); // true
alert(startDate2.getTime() == startDate3.getTime()); //true

Also consider using Date constructor taking explicit year/month/date number rather then relying on string representation (see: Date.parse()). And remember that dates in JavaScript are always represented using client (browser) timezone.

Solution 3:

You do not need to use the getTime method- you can subtract a date object from another date object. It will return the milliseconds difference(negative, if the second is a later date)

var startDate1 = new Date("02/10/2012");
var startDate2 = new Date("01/10/2012");

var diff= (startDate1 -startDate2)

// evaluates to 0 if the dates have the same timestamp

Solution 4:

you can compare the actual milliseconds :

alert(startDate2.getTime() === startDate3.getTime());