How to compare two equal dates in JavaScript

Freddy Montes - Frontend Developer, Designer and TeacherFreddy Montes|

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.

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:

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:

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".

Then comparing the identical number value gives us true.


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.


Thank your read this blog post. Any feedback or question hit me up on Twitter.

Tweet Me

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