Comparing two dates with JavaScript

To compare two dates in JavaScript, you can use the built-in Date object and its ‘getTime()‘ method, which returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Here’s an example of how you can compare two dates in JavaScript:

const date1 = new Date('2022-01-01');
const date2 = new Date('2021-01-01');

if (date1.getTime() > date2.getTime()) {
  console.log('Date 1 is later than Date 2');
} else if (date1.getTime() < date2.getTime()) {
  console.log('Date 1 is earlier than Date 2');
} else {
  console.log('Date 1 is the same as Date 2');
}

This code will create two Date objects for the dates ‘2022-01-01’ and ‘2021-01-01’, and then compare them using the ‘getTime()‘ method. The if statement will output ‘Date 1 is later than Date 2’ if the first date is later than the second, ‘Date 1 is earlier than Date 2’ if the first date is earlier than the second, and ‘Date 1 is the same as Date 2’ if the two dates are equal.

You can also use the > and < operators directly on the dates themselves, rather than using the ‘getTime()‘ method:

if (date1 > date2) {
  console.log('Date 1 is later than Date 2');
} else if (date1 < date2) {
  console.log('Date 1 is earlier than Date 2');
} else {
  console.log('Date 1 is the same as Date 2');
}

This will give the same result as the previous example.

ALSO SEE : How do I format a date in JavaScript?

Leave a Comment