To compare two dates in JavaScript, you can directly use comparison operators like <, >, <=, >=, or ===. JavaScript treats Date objects as values, so you can compare them as you would compare numbers or strings.
Here’s an example of how you can compare two dates:

// Create two date objects
const date1 = new Date('2023-12-31');
const date2 = new Date('2023-01-01');

// Compare the two dates
if (date1 > date2) {
 console.log('date1 is later than date2');
} else if (date1 < date2) {
 console.log('date1 is earlier than date2');
} else {
 console.log('date1 is equal to date2');
}

In this example:

  • We create two Date objects representing different dates.
  • We then use comparison operators to compare the two dates.
  • If date1 is later than date2, it will print ‘date1 is later than date2’.
  • If date1 is earlier than date2, it will print ‘date1 is earlier than date2’.
  • If both dates are equal, it will print ‘date1 is equal to date2’.

This approach works because JavaScript automatically converts Date objects to their underlying time values (milliseconds since the Unix epoch) when comparing them. Therefore, you can directly compare Date objects using comparison operators.

Support On Demand!

JavaScript