Javascript programming articles and tutorials for beginner | Anjan Dutta

How to compare dates in javascript

How to compare dates in javascript

To compare dates we can use comparison operators in javascript.

The best practice is to convert a date into a timestamp before comparison.

Because all the comparison operators do not work correctly on a date object.

For instance, a date object works correctly with the below operators.

  • > Greater than
  • < Less than
  • <= Less than or equal to
  • >= Greater than or equal to

See the below code example.

var date1 = new Date();
var date2 = new Date(date1);
console.log(date1);
console.log(date1);
date1 > date2; // false
date1 >= date2; //true

Both of the outputs are correct.

See the below image for console output.

correct-output

But, the date object doesn't give the right output when compared with the below operators.

  • == The equality operator
  • != inequality operator
  • === Identity operator
  • !== strict inequality operator

See the below code example.

var date1 = new Date();
var date2 = new Date(date1);
console.log(date1);
console.log(date1);
date1 === date2; //false
date1 !== date2; //true

Both of the outputs are wrong.

See the below image for console output.

incorrect-output

So, to make the code uniform for all types of conversions, we must convert the date into timestamp first and then any of the comparison operators will work.

var date1 = new Date();
var date2 = new Date(date1);
var dt1 = date1.getTime();
var dt2 = date2.getTime();

date-time-comparison

Timestamps work with any operator so it is easy to maintain a uniformity this way.

Edit this page on GitHub