How to Compare Two Dates With JavaScript

JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC. 

The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.

The ==, !=, ===, and !== operators require you to use date.getTime() as in:

var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();

to be clear just checking for equality directly with the date objects won't work.

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2);   // prints false (wrong!) 
console.log(d1 === d2);  // prints false (wrong!)
console.log(d1 != d2);   // prints true  (wrong!)
console.log(d1 !== d2);  // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

Here you can find more about the date.getTime() documentation

1 Comments

  1. It should have the explanation why this behaviour happens.
    Sp why is (d1 == d2) wrong?

    When we are using new Date we creating new Objects. Our variables are holding the reference to this Object. So this will always be wrong. The reference cant be the same because both Objects are valid and stored somewhere in our memory.

    So we have to take the real value we want to compare and this is in this case getTime()

    :)

    ReplyDelete
Previous Post Next Post