Compare dates in JS
Compare dates in JS

Learn how to compare two dates in JavaScript with various methods by Saruque Ahamed Mollick.

This tutorial details the methods for comparing two dates in JavaScript.

The principal methods or "functionalities" described for date comparison are:

  1. Using Relational Operators: You can compare two dates to determine which one is greater or smaller using the relational operators: <, >, <=, and >=. Examples demonstrate that comparing date1 (2018-05-26) to date2 (2018-05-23) using these operators yields the expected boolean output (e.g., date1 > date2 is true, and date1 < date2 is false).

  2. Using getTime() for Equality Comparison: You cannot use the equality or inequality operators (==, !=, !==, ===) directly to compare the value of a date object. If two dates with identical values are compared using ==, the result will be false. If you want to use these equality operators to compare dates, you must employ the getTime() method. When getTime() is used on both dates (e.g., date1.getTime() == date2.getTime()), the comparison successfully yields true for matching dates.