P粉7941776592023-08-04 15:33:36
Use the getTime() method to compare dates, which returns the number of milliseconds since the epoch (i.e. a number) for comparison:
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 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.
P粉9905682832023-08-04 12:15:10
This is because in the second case, the actual date objects are compared and the two objects are never equal. Cast them to numbers:
alert( +startDate2 == +startDate3 ); // true
If you want to convert it to a number more explicitly, you can use one of the following methods:
alert( startDate2.getTime() == startDate3.getTime() ); // true
oor
alert( Number(startDate2) == Number(startDate3) ); // true
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.