Sometimes, we want to compare JavaScript Date objects.
In this article, we’ll look at how to compare JavaScript Date objects.
How to compare JavaScript Date objects?
To compare JavaScript Date objects, we convert the dates to timestamps before we compare them.
For instance, we write
console.log(+startDate2 === +startDate3);
console.log(startDate2.getTime() === startDate3.getTime());
console.log(Number(startDate2) === Number(startDate3));
to use +
, getTime
or Number
to convert the startDate2
and startDate3
date objects into timestamps in milliseconds before we compare them.
Timestamps are integers, so we can compare them with the ===
operator.
Conclusion
To compare JavaScript Date objects, we convert the dates to timestamps before we compare them.