Comparing two dates in JavaScript using the loose or strict equality operators (==
or ===
) is not recommended for most cases. Equality operators compare the Date
object references, resulting in false
, even if the date values are the same:
const a = new Date(2022, 01, 10);
const b = new Date(2022, 01, 10);
a === b; // false
One way to compare two Date
values is using the Date.prototype.getTime()
method. This method returns a number indicating the number of milliseconds elapsed since the Unix Epoch:
const a = new Date(2022, 01, 10);
const b = new Date(2022, 01, 10);
a.getTime() === b.getTime(); // true
As mentioned before, Date.prototype.getTime()
is one way to compare two Date
values. It's not the only one way to compare them. Other options are the following:
Date.prototype.toISOString()
Date.prototype.toUTCString()
Date.prototype.toLocaleDateString()
provided you use the same localeAll of these methods produce consistent results, but we still recommend Date.prototype.getTime()
due to its simplicity.
Would you like to help us improve 30 seconds of code?Take a quick survey
Snippet collection
Comparing values in JavaScript is one of the most common tasks, yet it has a lot of things you should bear in mind.
JavaScript, Object
Learn how you can compare two objects in JavaScript using various different techniques.
JavaScript, Array
Learn how you can compare two arrays in JavaScript using various different techniques.
JavaScript, Date
Calculates the difference (in months) between two dates.