How to Compare Two Dates in JavaScript

Here are the ways to compare two dates in JavaScript.

  1. Using the “getTime()” method
  2. Using the “Date()” Object 

Method 1: Using the getTime() method

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

To handle equality comparison, you can use the date object alongside the “getTime()” method, which returns the number of milliseconds.

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

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

Method 2: Using the Date Object

You can also use the Date object(Date()) to compare two dates in JavaScript.

let date1 = new Date()
let date2 = new Date("07/04/2021")

if (date1 < date2) {
  console.log("Date1 is less than Date2");
} else if (date1 > date2) {
  console.log("Date1 is greater than Date2");
} else {
  console.log(`Both dates are equal`);
}

Output

Date1 is greater than Date2

How to Perform Specific Date Comparisons

To compare specific date values like the year, you can use the “.getYear()” date method.

let date1 = new Date("06/05/2022").getYear();
let date2 = new Date("07/04/2021").getYear();

if (date1 < date2) {
  console.log("Date1 is less than Date2 in terms of year");
} else if (date1 > date2) {
  console.log("Date1 is greater than Date2 in terms of year");
} else {
  console.log(`Both years are equal`);
}

Output

Date1 is greater than Date2 in terms of year

That’s it.