When comparing date objects in JavaScript, I found that it doesn't return true even when comparing identical dates.
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 do I compare these dates for equality? I want to use a native JavaScript Date object instead of any third-party library because it is not appropriate to use a third-party JavaScript library just to compare dates.
Use the getTime() method to compare dates, which returns the number of milliseconds since the epoch (i.e. a number) for comparison:
Also, consider constructing Date objects using explicit year/month/day numbers rather than relying on string representations (see: Date.parse()). And remember, dates in JavaScript are always represented using the client's (browser's) time zone.
This is because in the second case, the actual date objects are compared and the two objects are never equal. Cast them to numbers:
If you want to convert it to a number more explicitly, you can use one of the following methods:
oor
is a reference to the specification §11.9.3 Abstract Equality Comparison Algorithm, basically it says that when comparing objects, it is true only if obj1 == obj2 refers to the same object, otherwise the result is false.