Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  128] [ 5]  / answers: 1 / hits: 91910  / 13 Years ago, fri, september 30, 2011, 12:00:00

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.


More From » javascript

 Answers
14

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.


[#89849] Wednesday, September 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marib

Total Points: 596
Total Questions: 120
Total Answers: 95

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
;