How to compare two equal dates in JavaScript

The Date object in JavaScript is quite robust for working with dates, it allows you to compare if a date is greater or smaller than another, but when trying to compare if it is equal it fails.

Let's see an example.

const dateA = new Date("6/01/2023")
const dateB = new Date("6/01/2022")

console.log(dateA > dateB) // true
console.log(dateA < dateB) // false
console.log(dateA === dateB) // false - although it seems correct it is not.

You see this code and think it's right, but it turns out that the one that compares whether the dates are the same is wrong. Let's look at another example:

const dateA = new Date("6/01/2022")
const dateB = new Date("6/01/2022")

console.log(dateA === dateB) // false - even though they are the same

The two dates are the same, but the objects are different and that is what is being compared, not the dates but the objects.

Let's see an example of how to compare:

const dateA = new Date("6/01/2022").getTime()
const dateB = new Date("6/01/2022").getTime()

console.log(dateA === dateB) // true - works!!!!

The getTime() method

JavaScript's getTime() method returns the number of milliseconds of the date since midnight on January 1, 1970, i.e. since the epoch "date".

const dateA = new Date("6/01/2022").getTime() // 1654063200000
const dateB = new Date("6/01/2022").getTime() // 1654063200000

console.log(dateA === dateB) // 1654063200000 === 1654063200000

Then comparing the identical number value gives us true.

Conclusion

When working with dates in JavaScript, remember that the === operator does not work for comparing dates, but you can use the getTime() method to get the number of milliseconds of the date and compare those values.

Copyright © 2024. Design and code by myself with Next.js. Fork it and create yours