Compare JavaScript Date objects
P粉724737511
P粉724737511 2023-08-03 17:28:16
0
2
597
<p>When comparing date objects in JavaScript, I found that it doesn't return true even when comparing identical dates. </p> <pre class="brush:php;toolbar:false;">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</pre> <p>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. </p>
P粉724737511
P粉724737511

reply all(2)
P粉794177659

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粉990568283

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template