Comparing two dates in JavaScript.

This is a short and simple guide on how to compare two dates in JavaScript. This is useful if you need to figure out which date is greater or which date occurred first.

Firstly, let’s create two JavaScript Date objects:

As you can see, the first date is greater than the second date because it occurred nearly seven years later. However, what if we need to compare these two dates using JavaScript?

The getTime() method.

The getTime() method allows us to get the Unix Timestamp of a Date object. This method will return the number of milliseconds that have passed between the “Unix Epoch” and the date in question. Essentially, it will give us a numerical value that we can do some quick comparisons with.

Take a look at the following JavaScript code:

Above, I created a simple IF/ELSE statement that compares the Unix Timestamp of each Date object. If the timestamp of date one is greater than the timestamp of date two, then it means that date one occurred later. This is because more milliseconds have passed between the Unix Epoch and date one than the Unix Epoch and date two.

If you run the code snippet above, you will see that the first IF statement is proven TRUE and that the following output is logged to the browser’s console:

This is because the date “2019-01-01” is greater than “2012-03-02”.

By the way, there is no need to stick to the YYYYMMDD format. You can also create a Date object using a date string like so:

Note that the getTime() method is also useful because it will return the timestamp in a UTC format. This means that we shouldn’t run into any annoying issues with timezones while comparing dates.

That’s it! Feel free to modify the dates above and see how it changes the console output!

Facebook Comments