How to Compare Two Dates in JavaScript

To compare two dates in JavaScript, you can convert the Date objects to their numeric representation using the “getTime()” method, which returns the number of milliseconds since January 1, 1970 (Unix Epoch), and then compare the resulting numeric values using “comparison operators” like <, >, ==, !=, <=, or >=.

Example 1

const date1 = new Date('2023-01-21');
const date2 = new Date('2023-01-22');

// Check if date1 is equal to date2
console.log(date1.getTime() === date2.getTime());

// Check if date1 is before date2
console.log(date1.getTime() < date2.getTime());

// Check if date1 is after date2
console.log(date1.getTime() > date2.getTime());

Output

false
true
false

In this code, we created two Date objects, date1, and date2, representing April 21, 2023, and April 22, 2023, respectively.

In the next step, we used the “getTime()” method to get their numeric representations and compare them using various comparison operators.

The output shows that date1 is not equal to date2, date1 is before date2, and date1 is not after date2.

Example 2

Remember that when comparing dates, it’s also essential to consider the time component.

To compare dates without considering the time, you can first set the time part to 0 using the “setHours()” method:

const date1 = new Date('2023-01-22T12:00:00');
const date2 = new Date('2023-01-22T00:00:00');

date1.setHours(0, 0, 0, 0);
date2.setHours(0, 0, 0, 0);

console.log(date1.getTime() === date2.getTime());

Output

true

In this code, we first set the time components of date1 and date2 to 0 using the “setHours(0, 0, 0, 0)” method, effectively comparing only their date parts.

The comparison result is true, suggesting that the two dates are equal after disregarding their time components.

Leave a Comment