You Can Compare Dates In Javascript

Filip Vitas
3 min readJan 1, 2021

or how to compare dates in Javascript

Photo by Noel Broda on Unsplash

I stumbled upon the blog post named You Cannot Compare Dates In Javascript.
The title is a bit misleading and it doesn’t give a reason, why we can’t compare them. Maybe we should not compare Date objects directly, but we can and should compare dates with Javascript.

It’s a coercion 🤫

Coercion is the conversion of the values from one type to another. And to understand date comparison, we need to understand how coercion works.
In the previous code example, we have implicit coercion.
When using comparison operators (>, <, <=,>=) there will be an implicit numeric conversion from date object to a number.

Date.prototype[Symbol.toPrimitive](hint)

This function is called when operators need to convert a Date object to a primitive value.

We have a conversion to a number and that’s why we have:

Equality operator

Operator == will coerce a Date object to a string if the other operand is a primitive value other than undefined, null and boolean.

But if we compare 2 objects of the same type, we will compare object references.

that’s why references are not the same

Solution

To be sure that we are comparing the same types, we can compare milliseconds. Both .getTime() and .valueOf() will get the number of milliseconds between 1 January 1970 00:00:00 UTC and the given date.

Timezones

Since .getTime() is converting milliseconds from UTC, we can even compare the dates from different timezones.

We can compare dates, but make sure you know what you are doing.
And you don’t need moment.js for such a small task.

Thanks for reading! If you like the article, give a clap, or two, or 50👏
Leave a comment below if you have any questions or say hi on
Twitter.

--

--