You Can Compare Dates In Javascript

or how to compare dates in Javascript

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

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.

Image for post
Image for post

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

Image for post
Image for post

that’s why references are not the same

Image for post
Image for post

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.

Image for post
Image for post
Image for post
Image for post

Timezones

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

Image for post
Image for post

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.

Coffee Driven Software Developer @SBGenomics

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store