Comparing Two Dates in JavaScript

How to compare two dates using JavaScript?

Using the getTime() method:
The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. You can use this method to compare two dates by converting them to milliseconds since January 1, 1970, and then comparing the values.

const date1 = new Date('2022-05-17');
const date2 = new Date('2022-05-18');

if (date1.getTime() === date2.getTime()) {
    console.log('Dates are equal');
} else if (date1.getTime() > date2.getTime()) {
    console.log('Date1 is after Date2');
} else {
    console.log('Date1 is before Date2');
}

That’s a great method, Ian. Another way to compare dates is by using the comparison operators directly on Date objects. JavaScript allows this because the comparison operators implicitly call the valueOf() method of the Date objects, which returns the numeric value of the date. Here’s how you can do it:

const date1 = new Date('2022-05-17');
const date2 = new Date('2022-05-18');

if (date1 === date2) {
    console.log('Dates are equal');
} else if (date1 > date2) {
    console.log('Date1 is after Date2');
} else {
    console.log('Date1 is before Date2');
}

Both of those methods are quite effective! Another approach you might consider is using the toDateString() method. This method returns the date portion of a Date object as a human-readable string in the local time zone. It’s useful when you only care about the date part, ignoring the time. Here’s how you can do it:

const date1 = new Date('2022-05-17');
const date2 = new Date('2022-05-18');

if (date1.toDateString() === date2.toDateString()) {
    console.log('Dates are equal');
} else if (date1.toDateString() > date2.toDateString()) {
    console.log('Date1 is after Date2');
} else {
    console.log('Date1 is before Date2');
}