Comparing Two Dates in JavaScript: A Guide

Navigate to:

Comparing two dates in JavaScript—this sounds like the type of task that should be a walk in the park. In reality, such comparisons can be tricky. The reason for that is twofold.

First, time handling is a harder task than many developers give it credit for. Secondly, JavaScript is a language known for its…well, idiosyncrasies.

So, if you’re somewhat puzzled by date comparisons in JavaScript, know that (a) you are not alone, and (b) this post was made for you. We’ll open with a brief explanation of date objects in JavaScript and how they work. After that, we’ll dive into a tutorial where you’ll learn how to perform date comparisons in JavaScript using several methods.

Let’s dig in.

JavaScript dates: the fundamentals

The basic workings of date and time manipulation in JavaScript are easy to understand. Everything revolves around Date, which is a built-in JavaScript object. Despite its name, the Date object stores both date and time information.

Let’s see a quick example.

let now = new Date();

console.log(now);

If I run the code above using Node.js, it displays a result like this: 2024-02-24T14:39:56.879Z. When we instantiate a new Date object without any parameters, the object is set to the current date and time according to the system’s clock. The displayed date was formatted according to theISO-8601 standard, and it is in UTC. UTC is also known as Zulu Time, hence the Z at the end.

Using Google Chrome DevTools, the behavior is different. Here’s a screenshot: The result in this situation is Sat Feb 24 2024 11:55:12 GMT-0300 (Horário Padrão de Brasília). It displays the date in my time zone (Brazil Standard Time). To clarify, the Date object itself doesn’t contain any information about the time zone name. It does contain the offset to UTC—that is, how many hours we are apart from UTC.

I can show this with a small change to the previous example:

let now = new Date();

console.log(now.getTimezoneOffset());

After running the code above, I get 180 as a result. This number means the number of minutes we are apart from UTC—in other words, three hours. Very unintuitively, though, it returns a positive number if we’re behind UTC, and a negative one if we’re past it.

Another relevant characteristic of Date in JavaScript is that this object, unlike equivalents in many other languages, is mutable—in other words, it can change:

let date = new Date('2024-02-01T14:20:10Z');

console.log(date);

date.setHours(15);

console.log(date);

date.setFullYear(2025);

console.log(date);

And, for the result:

2024-02-01T14:20:10.000Z

2024-02-01T18:20:10.000Z

2025-02-01T18:20:10.000Z2024-02-01T14:20:10.000Z

2024-02-01T18:20:10.000Z

2025-02-01T18:20:10.000Z

So, to summarize, the Date JavaScript object:

  • contains information about date and time despite its name
  • doesn’t know to which time zone it belongs, but contains the offset to UTC
  • is mutable

Now, let’s move on to date comparisons!

How can I compare two dates in JavaScript?

First, answer this: what will the following code display?

let date1 = new Date('2024-02-01T14:20:10Z');

let date2 = new Date('2024-02-01T14:20:10Z');

console.log(date1 == date2 ? "Equal" : "Not Equal");

It might surprise you, but the answer is Not Equal. The explanation for this behavior is simple: Date is an object and, as such, a reference type. When used on objects, the equality (==) operator evaluates whether the references they store point to the same object in memory. In the code above, we instantiate Date twice, meaning there are two objects in memory, each with its unique reference, assigned to a variable.

We’ll have to use the getTime() method to do this right. This method returns an integer number, which is the number of milliseconds since the Unix Epoch—that is, January 1, 1970, 00:00:00 UTC. You can then use this number to perform the comparison:

let date1 = new Date('2024-02-01T14:20:10Z');

let date2 = new Date('2024-02-01T14:20:10Z');

console.log(date1.getTime() == date2.getTime() ? "Equal" : "Not Equal");

Number is a primitive type, so the equality operator behaves as you would expect, and the code displays Equal.

Comparing dates with operators

You’ve just seen that using the equality operator to compare dates in JavaScript doesn’t work—unless you’re trying to compare their references. But what about the other operators? Can you evaluate whether a Date comes first or before another one, using the greater-than (>) and lesser-than (<) operators? Yes, absolutely.

let januaryFirst = new Date(2024, 0, 1);

let februaryFirst = new Date(2024, 1, 1);

if (februaryFirst > januaryFirst) {

` console.log(“Yes, indeed February comes after January.”);`

}

if (januaryFirst < februaryFirst) {

` console.log(“Also, indeed January comes before February.”);`

}

Yes, the code above is correct. When you pass the value month as a parameter in JavaScript, it has to be zero-based. When I run the code above, it displays the expected messages:

Yes, indeed February comes after January.

Also, indeed January comes before February.

OK, great. But what about the following piece of code? Without running it, can you tell me what will be displayed?

let first = new Date(2024, 1, 10, 14, 5, 25);

let second = new Date(2024, 1, 10, 14, 5, 25);

if (first >= second) {

` console.log(“The first date is after the second, or they’re the same.”);`

} else {

` console.log(“The first date comes before the second one.”);`

}

Enough with the mystery. Here’s the answer:

The first date is after the second, or they're the same.

Well, it seems that, in this case, the equality operator does work. What is happening here? Keep in mind that JavaScript is not only a dynamic, but a weakly typed language. It often types coercions on your behalf, with results that can be confusing but sometimes quite useful.

In this case, when you use the greater-than-or-equal-to or lesser-than-or-equal-to operators on Date objects, JavaScript converts their values to numbers, calling the getTime() method. Then, it’s just a matter of comparing the numbers as usual.

Can you convert a string into a date for comparison in JavaScript?

Sometimes you have dates and times stored as strings and you need to compare them. The recommended approach here is to convert them to Date objects and then compare them. Of course, the success of this approach would depend on the format of the strings.

If you’re lucky, the values in the strings will be formatted using the ISO-8601 standard, in which case the comparison is a breeze:

let first = new Date('2024-02-24T13:02:05Z');

let second = new Date('2024-02-25T13:02:05Z');

console.log(first.getTime() == second.getTime() ? "Equal": "Different");

What if your string isn’t in this format? Well, you’re out of luck when it comes to native JavaScript support. In this case, you can either rely on third-party libraries or write your parsing utilities. So, the tip here is to stick to ISO-8601 as much as possible!

Can you compare dates without the time component?

As you’ve seen, the Date object stores the date and time of day. But often, you wish you could compare two Date objects, disregarding the time component. How do you go about that?

There are two main solutions. One is to take advantage of Date’s mutability, set its hours to 0, and then perform the comparison:

let first = new Date('2024-02-24T13:02:05Z');

let second = new Date('2024-02-24T18:02:05Z');

first.setHours(0, 0, 0);

second.setHours(0, 0, 0);

console.log(first.getTime() === second.getTime() ? 'Same' : 'Different');

The solution above works. It has the advantage of being simple and not requiring a lot of code. It has the big disadvantage of mutating the values, which can bring unintended consequences and, as such, should be avoided most of the time.

The other alternative is to decompose the date into its values for year, month, and day and then compare those:

function compareDatesOnly(date1, date2) {

` const d1 = new Date(date1);`

` const d2 = new Date(date2);`

` const year1 = d1.getFullYear();`

` const month1 = d1.getMonth();`

` const day1 = d1.getDate();`

` const year2 = d2.getFullYear();`

` const month2 = d2.getMonth();`

` const day2 = d2.getDate();`

` return year1 === year2 && month1 === month2 && day1 === day2;`

}

let date1 = '2024-02-24T13:02:05Z';

let date2 = '2024-02-24T18:02:05Z';

console.log(compareDatesOnly(date1, date2) ? 'Same' : 'Different');

In the code above, we use the getFullYear(), getMonth(), andgetDate() methods to extract the individual date components from both objects and then compare them one by one.

This second solution uses more code, but it’s a better approach because it doesn’t mutate the original objects.

JavaScript date handling, wrapped up

In this post, you’ve learned how to compare dates in JavaScript. You’ve learned about the Date object, how to instantiate it, and how it works. You’ve learned about some of the pitfalls you should avoid.

Let’s review them and add some more:

  • Remember that months are zero-based when passed as parameter values.
  • Don’t use the equality operator to compare two Date objects; instead, convert them with getCurrentTime() and then make the comparison.
  • When you instantiate a Date with invalid values—such as March 31—it doesn’t fail; instead, it silently “overflows” into the next valid value. Be mindful of this and always validate external input.
  • Stick to UTC and ISO-8601 when storing date values.

Time and date manipulation is a fascinating and messy topic. This post only scratched the surface. As a next step, continue exploring the Date object, and then start exploring the JavaScript Internationalization API. You can also look into using InfluxDB for time series data using the JS client library.

This post was written by Carlos Schults. Carlos is a skilled software engineer and an accomplished technical writer for various clients. His passion is to get to the bottom (the original source) of things and captivate readers with approachable and informative technical content.