search

Home  >  Q&A  >  body text

Compare JavaScript Date objects

<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粉724737511P粉724737511489 days ago542

reply all(2)I'll reply

  • P粉794177659

    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.

    reply
    0
  • P粉990568283

    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.

    reply
    0
  • Cancelreply