How To Compare Two Dates In JavaScript

JavaScript

02/02/2023


When it comes to comparing two dates, you should ask yourself: Do I want to include the time of the day in the comparison itself? If the answer is yes, the easiest way of performing a comparison is by using comparison signs (e.g. > and >=).

Comparing dates with time

JAVASCRIPT
const date1 = new Date()
const date2 = new Date()
return date1 < date2

However, be careful when checking for equality! An equality check of two different objects will always return false as JavaScript performs an equality of reference instead of an equality of value.

Instead, use the .getTime method to retrieve the Unix timestamp of the date.

JAVASCRIPT
return date1.getTime() === date2.getTime()

Comparing days only

On the other hand, if you wish to ignore the time in the comparison, .setHours is your guy! What to do? Simply set the time to midnight for any dates being compared.

JAVASCRIPT
const dateA = new Date(date1)
const dateB = new Date(date2)
dateA.setHours(0, 0, 0, 0)
dateB.setHours(0, 0, 0, 0)
return dateA > dateB

Notice how I copied both dates into new variables dateA and dateB. The reason for doing so is that setHours will mutate the original dates, which will cause undesired side-effects in your application if not accounted for. In addition, if you wish to check for equality, use .getTime as in the previous section.


WRITTEN BY

Code and stuff