Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Date Object Comparison

Tags:

javascript

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.

like image 812
Harshana Avatar asked Sep 30 '11 06:09

Harshana


People also ask

Can we compare date object in JavaScript?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

How do you compare date objects?

For comparing the two dates, we have used the compareTo() method. If both dates are equal it prints Both dates are equal. If date1 is greater than date2, it prints Date 1 comes after Date 2. If date1 is smaller than date2, it prints Date 1 comes after Date 2.


1 Answers

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.

like image 196
RobG Avatar answered Nov 08 '22 10:11

RobG