JavaScript Compare Dates: From Chaos to Clarity
Tags: javascript, webdev, programming, tutorial
Published: 2024-05-06 04:30:25


If you are a web developer, you might have wondered how JavaScript compares dates in your projects. Comparing dates is a common task that can be tricky and frustrating if you don’t know the best practices and methods.

Comparing dates in JavaScript can be tricky. There are many factors to consider, such as the format, the time zone, the accuracy, and the purpose of the comparison. How do you know if two dates are equal, greater than, or less than each other? How do you compare dates without time or by day? How do you compare dates in different time zones?

In this blog post, you will learn:

- JavaScript date comparison methods and tips
- Comparing dates without considering the time in JavaScript
- Comparing dates and times in JavaScript
- How to check if two dates have the same day in JavaScript
- Dealing with different time zones when comparing dates in JavaScript
- Using libraries to simplify date comparison in JavaScript

By this post's end, you can compare dates in JavaScript like a pro!

How do you compare dates in JavaScript?
---------------------------------------

Do you want to learn how to compare dates in JavaScript? It’s easy and fun with the [JavaScript Date](https://www.rajamsr.com/javascript-date/) object and the `getTime()` method.

![JavaScript Date Object Methods](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdv5u15bo7jfxathu0hb.png)


These are the best methods for working with dates and times in JavaScript. Let me show you why and how to use them. The `Date` object is a special kind of object that stores a date and time. You can make a new Date object by giving it a string, a number, or nothing at all. For example:

```
let date1 = new Date();             // Current date and time
let date2 = new Date("6/01/2022");  // Specific date string
let date3 = new Date(2022, 5, 1);   // Specific date (year, month, day)
```


The getTime() method is a wonderful way to work with dates in JavaScript. It gives you a number that represents the exact moment in time when a date object was created. This number is the amount of milliseconds that have passed since the start of 1970, which is a special date in computer science. Why is this number so useful? Because you can easily compare different dates with each other using simple math. You can check if one date is before, after, or equal to another date by comparing their numbers. For example:

```
let date1 = new Date();
let date2 = new Date("6/01/2022");
let date3 = new Date(2022, 5, 1);
console.log(date1.getTime() > date2.getTime());  // false
console.log(date2.getTime() == date3.getTime()); // true
console.log(date3.getTime() < date1.getTime());  // false
```

![JavaScript Date Comparison](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1uu4ikfz2nawutnc3ugs.png)

Comparing dates is easy and accurate with the [JavaScript Date constructor](https://www.rajamsr.com/javascript-date-constructor/) and the `getTime()` method. You can use any format, `timezone`, or leap year for the dates. And you don’t need any extra libraries like `moment.js` that can make your code heavier.

Compare dates without time in JavaScript
----------------------------------------

How do you compare dates in JavaScript without caring about the time? You might need this for birthdays, coupons, or other things that depend on the date only.

There are two ways to do this in JavaScript: with strings or with numbers. Let me show you how they work.

### 1. Compare dates without time using strings

Here’s a cool trick to compare dates without time in JavaScript. Just turn the date objects into [JavaScript strings](https://www.rajamsr.com/javascript-string/) that show only the date. How? Use the `toDateString()` method. It gives you a string like this: `“Weekday Month Day Year”`. For example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1String = date1.toDateString();           // "Tue Jan 29 2024"
let date2String = date2.toDateString();           // "Tue Jan 29 2024"
```


Now, you can [compare the strings](https://www.rajamsr.com/javascript-string-equality/) using the comparison operators (<, >, ==, etc.). For example:

```
console.log(date1String === date2String); // Output: true
console.log(date1String < date2String);   // Output: false
console.log(date1String > date2String);   // Output: false
```

![JavaScript Compare Strings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zn6v1b4g7gwpcbhdtwqg.png)

As you can see, the strings are equal, because they have the same date part, even though the time part is different.

### 2. Compare dates without time using numbers

You can also compare dates without time in JavaScript by turning them into numbers. These numbers show how many milliseconds have passed since `January 1, 1970`. You can get these numbers by using the `getTime()` method. It gives you a number like this: `Milliseconds`.

Here’s an example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1Number = date1.getTime();                // 1709286888000
let date2Number = date2.getTime();                // 1709332800000
```


Now, you can compare the numbers using the comparison operators (<, >, ==, etc.). For example:

```
console.log(date1Number === date2Number);   // Output: false
console.log(date1Number < date2Number);     // Output: true
console.log(date1Number > date2Number);     // Output: false
```


Look at these numbers. They are not the same, right? That’s because they have different times, even though the dates are the same.

But how can you compare dates without times using numbers? You can do it by rounding down the milliseconds to the closest day. You can use the [JavaScript Math.floor()](https://www.rajamsr.com/javascript-math-floor/) function for that. It gives you the biggest whole number that is smaller or equal to our number. For example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z");  // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1Number = date1.getTime();                // 1709286888000
let date2Number = date2.getTime();                // 1709332800000
let numberOfMillisecondsPerDay = (1000 * 60 * 60 * 24);
let date1Day = Math.floor(date1Number / numberOfMillisecondsPerDay); // Output: 19767
let date2Day = Math.floor(date2Number / numberOfMillisecondsPerDay); // Output: 19767
```


Now, you can compare the numbers using the comparison operators (<, >, ==, etc.). For example:

```
console.log(date1Day === date2Day); // Output: true
console.log(date1Day < date2Day);   // Output: false
console.log(date1Day > date2Day);   // Output: false
```


As you can see, the numbers are equal, because they have the same date part, after rounding down to the nearest day.

Compares dates with time in JavaScript
--------------------------------------

Sometimes you need to compare dates and times in JavaScript. This is handy when you care about the exact moment of the date, not just the day. For example, you might want to see if an event has started, ended, or is still going on, or if a deadline is over or coming soon.

You can compare dates and times in JavaScript in two main ways: using strings or using numbers. Let’s learn how they work.

### 1. Compare dates with time using strings

You can compare dates with time in JavaScript by using `ISO 8601 format` strings. They are easy to read and understand. They look like in the date format `YYYY-MM-DDTHH:mm:ss.sssZ`. Here’s an example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1String = date1.toISOString();            // "2024-01-29T03:34:48.000Z"
let date2String = date2.toISOString();            // "2024-01-29T15:00:00.000Z"
```


Now, you can compare the strings using the comparison operators (<, >, ==, etc.). For example:

```
console.log(date1String === date2String); // Output: false
console.log(date1String < date2String);   // Output: true
console.log(date1String > date2String);   // Output: false
```


As you can see, the strings are not equal, because they have different time parts, even though the date part is the same.

### 2. Compare dates with time using numbers

Here’s a fun way to compare dates in JavaScript: turn them into numbers! How? Just use the `getTime()` method. It gives you a number that means “`how many milliseconds have passed since January 1, 1970`”. Like this:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1Number = date1.getTime();                // 1709286888000
let date2Number = date2.getTime();                // 1709332800000
```


Now, you can compare the numbers using the comparison operators (<, >, ==, etc.). For example:

```
console.log(date1Number === date2Number); // Output: false
console.log(date1Number < date2Number);   // Output: true
console.log(date1Number > date2Number);   // Output: false
```


As you can see, the numbers are not equal, because they have different time parts, even though the date part is the same.

Compare dates by day in JavaScript
----------------------------------

How awesome is it to compare dates by day in JavaScript? You can do amazing things like grouping data by date or showing a calendar of events. You just need to use the date components. Let me show you how.

Using Date Components
---------------------

One way to compare [dates by day in JavaScript](https://www.rajamsr.com/javascript-date-add-days/) is to use the date components, such as the day, weekday, month, and year of a date object. You can get these components by using the `getDate()`, `getDay()`, `getMonth()`, and `getFullYear()` methods, which [return numbers in the format](https://www.rajamsr.com/javascript-format-numbers-with-comma/) `Day`, `Weekday`, `Month`, and `Year`. For example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1Day = date1.getDate();                   // 29
let date1Weekday = date1.getDay();                // 2
let date1Month = date1.getMonth();                // 0
let date1Year = date1.getFullYear();              // 2024
let date2Day = date2.getDate();                   // 29
let date2Weekday = date2.getDay();                // 2
let date2Month = date2.getMonth();                // 0
let date2Year = date2.getFullYear();              // 2024
```


Now, you can compare the numbers using the comparison operators (<, >, ==, etc.). For example:

```
console.log(date1Day === date2Day);         // Output: true
console.log(date1Weekday === date2Weekday); // Output: true
console.log(date1Month === date2Month);     // Output: true
console.log(date1Year === date2Year);       // Output: true
```


As you can see, the numbers are equal, because they have the same date components, even though the time part is different.

Compare dates in different time zones in JavaScript
---------------------------------------------------

You can adjust the hours and minutes to match the local time or the universal time. For example, you can show the local time of an event in another country, or make the user’s input consistent with a standard time.

To do this, you need to use the time zone offset. It’s a simple and powerful way to compare dates. Let me show you how.

Using Time Zone Offset
----------------------

You just need to use the time zone offset. That’s the difference in minutes between your local time and the `UTC (Universal Time)`. How do you get it? Easy! Just use the `getTimezoneOffset()` method. It gives you a number like this: `Minutes`. For example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1Offset = date1.getTimezoneOffset();      // 0
let date2Offset = date2.getTimezoneOffset();      // 0
```

![JavaScript Time Zones Offset](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5kgu0393vtmlxr0mkx6.png)


How do we compare dates in different time zones? Let’s say `date1` is in India and `date2` is in `Japan`. `India` is 5.5 hours ahead of UTC, and `Japan` is 9 hours ahead. So, the time zone offset for the `date1` is `+05:30`, and for the `date2` is `+09:00`. This means `date1` and `date2` have different offsets from UTC. Here’s an example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1Offset = date1.getTimezoneOffset();      // 0
let date2Offset = date2.getTimezoneOffset();      // 0
// Adjust the dates to the local time zones
date1.setTime(date1.getTime() + date1Offset * 60 * 1000); // Tue Jan 29 2024 09:04:48 GMT+0530
date2.setTime(date2.getTime() + date2Offset * 60 * 1000); // Tue Jan 29 2024 18:00:00 GMT+0900
// Get the new time zone offsets
date1Offset = date1.getTimezoneOffset();        // -330
date2Offset = date2.getTimezoneOffset();        // -540
```


`Date1` is `330` minutes ahead of UTC, so its offset is `-330`. `Date2` is `540` minutes ahead of UTC, so its offset is `-540`.

You can check which date is earlier or later with symbols like <, >, and ==. For example:

```
console.log(date1 === date2); // Output: false
console.log(date1 < date2);   // Output: true
console.log(date1 > date2);   // Output: false
```


As you can see, the dates are not equal, because they have different time zones, even though the UTC is the same.

Compare dates using libraries in JavaScript
-------------------------------------------

Comparing dates in JavaScript can be tricky. But don’t worry, some awesome libraries make it easy and fun. You can use them to write dates in natural language, relative time, or custom formats. How cool is that?

Some of the best libraries for date comparison are `Moment.js`, `Day.js`, and `date-fns`. Let’s explore how they work and what they can do for you.

### 1. Moment.js

[Moment.js](https://momentjs.com/) lets you do amazing things with dates and times in JavaScript. You can easily compare, change, and format them in different ways. For example, you can say things like `"today is Monday"` or `"3 hours ago"` or `"12/31/2020"`. To start with `Moment.js`, you need to install it and import it into your JavaScript project. For example:

```
// Install Moment.js using npm
npm install moment
// Import Moment.js in your JavaScript file
const moment = require("moment");
```

`Moment.js` makes it easy to compare dates. Just create moment objects from whatever you have: date objects, strings, or numbers. Use the `moment()` function with any arguments or formats you like. For example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
// Create a moment object from a date object
let moment1 = moment(date1); 
let moment2 = moment(date2);
// Create a moment object from a string in ISO 8601 format
let moment3 = moment("2024-01-29T03:34:48.000Z"); 
let moment4 = moment("2024-01-29T15:00:00.000Z"); 
// Create a moment object from a number in milliseconds
let moment5 = moment(1709286888000); 
let moment6 = moment(1709332800000);
```


You can do amazing things with `Moment.js`! You can compare different moments and see which one is earlier, later, or the same as another. You can use simple methods like `isBefore()`, `isAfter()`, `isSame()`, and more. They give you a true or false answer. Here’s an example:

```
console.log(moment1.isBefore(moment2));       // Output: true
console.log(moment1.isAfter(moment2));        // Output: false
console.log(moment1.isSame(moment2));         // Output: false
console.log(moment1.isSameOrBefore(moment2)); // Output: true
console.log(moment1.isSameOrAfter(moment2));  // Output: false
```


Look at that! When you compare objects with `moment`, they use UTC, just like date objects. But maybe you want to compare them with local time, or another time zone. No problem! You can change the time zone of the moment objects with `local()` or `utcOffset()`.

### 2. Day.js

`Day.js` lets you work with dates and times in JavaScript easily and quickly. It is like Moment.js, but smaller and faster. It also has many plugins that add more features and options. For example, you can say things like `"today is before yesterday"` or `"3 hours ago"` or `"12/31/2020"` with `Day.js`. To use `Day.js`, you need to download it and add it to your JavaScript project. For example:

```
// Install Day.js using npm
npm install dayjs
// Import Day.js in your JavaScript file
const dayjs = require("dayjs");
```


[Day.js](https://www.npmjs.com/package/dayjs) is awesome for comparing dates! You just need to make `dayjs` objects from whatever dates you have. You can use the `dayjs()` function with different inputs and formats. Here’s an example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); 
// Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); 
// Tue Jan 29 2024 15:00:00 GMT+0000
// Create a dayjs object from a date object
let day1 = dayjs(date1); 
let day2 = dayjs(date2);
// Create a dayjs object from a string in ISO 8601 format
let day3 = dayjs("2024-01-29T03:34:48.000Z"); 
let day4 = dayjs("2024-01-29T15:00:00.000Z");
// Create a dayjs object from a number in milliseconds
let day5 = dayjs(1709286888000); 
let day6 = dayjs(1709332800000);
```


You can easily compare `dayjs` objects with `Day.js`. It has awesome methods like `isBefore()`, `isAfter()`, `isSame()`, and more. They give you a true or false answer. For example:

```
consol.log(day1.isBefore(day2)); 		// Output: true
consol.log(day1.isAfter(day2)); 		// Output: false
consol.log(day1.isSame(day2)); 			// Output: false
consol.log(day1.isSameOrBefore(day2)); 	// Output: true
consol.log(day1.isSameOrAfter(day2)); 	// Output: false
```


`Dayjs` objects and date objects have the same UTC. That’s how we compare them. But sometimes you need a different time zone. No problem! Just use `local()` or `utcOffset()` to change the `dayjs` objects to the time zone you want.

### 3. Date-fns compare dates

[Date-fns](https://date-fns.org/) is a modern and modular library that lets you do amazing things with dates and times. You can parse, sort dates, and format them in any way you want. You can also use plugins to add more features, like natural language comparisons, relative time, or custom formats.

Using `date-fns` is easy. Just install it and import it into your project. Here’s how:

```
// Install date-fns using npm
npm install date-fns
// Import date-fns in your JavaScript file
const { compareAsc, compareDesc, format, 
	formatDistance, formatRelative, isAfter, 
	isBefore, isEqual, isSameDay, 
	isSameMonth, isSameYear } = require("date-fns");
```


You can compare dates with `date-fns` in different ways. You can use date objects, strings, or numbers. To make date objects from strings or numbers, use the Date object or `parseISO()`. For example:

```
let date1 = new Date("2024-01-29T03:34:48.000Z"); 
// Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); 
// Tue Jan 29 2024 15:00:00 GMT+0000
let date3 = parseISO("2024-01-29T03:34:48.000Z"); 
// Tue Jan 29 2024 03:34:48 GMT+0000
let date4 = parseISO("2024-01-29T15:00:00.000Z"); 
// Tue Jan 29 2024 15:00:00 GMT+0000
let date5 = parseISO(1709286888000); 
// Tue Jan 29 2024 03:34:48 GMT+0000
let date6 = parseISO(1709332800000); 
// Tue Jan 29 2024 15:00:00 GMT+0000
```


It has many handy functions like `compareAsc()`, `compareDesc()`, `isAfter()`, `isBefore()`, `isEqual()`, and more. They give you a number or a true/false value to show the result. For example:

```
console.log(compareAsc(date1, date2)); 	// Output: -1
console.log(compareDesc(date1, date2)); // Output: 1
console.log(isAfter(date1, date2)); 	// Output: false
console.log(isBefore(date1, date2)); 	// Output: true
console.log(isEqual(date1, date2)); 	// Output: false
console.log(isSameDay(date1, date2)); 	// Output: true
console.log(isSameMonth(date1, date2)); // Output: true
console.log(isSameYear(date1, date2)); 	// Output: true
```


You know how date objects use UTC, right? That’s how they compare with each other. But sometimes you need to use local time or another time zone. Don’t worry, you can do that too! Just use `utcToZonedTime()` or `zonedTimeToUtc()` to change the date objects to the time zone you want.

Conclusion
----------

In this blog post, you have learned how to compare dates in JavaScript using various methods and libraries. You have seen that comparing dates in JavaScript can be tricky, but also fun and expressive. You have learned how to compare dates without time, with time, by day, in different time zones, using natural language, relative time, or custom formats.

You have also learned how to use some of the most popular and useful libraries for working with dates in JavaScript, such as `Moment.js`, `Day.js`, and `date-fns`.

I hope you had fun reading this blog post and that you feel more confident and excited about comparing dates in JavaScript.

----------------------------
I hope you have found this blog post helpful and informative. If you have any questions, comments, or feedback, please feel free to leave them below. 😊

If you want to stay connected with me and get more updates on my work, you can follow me on different platforms.

[Website(rajamsr.com)](http://www.rajamsr.com/) | [X (Twitter)](https://twitter.com/rajamsrtweets) | [LinkedIn](https://www.linkedin.com/in/rajamsr/) | [Medium] (https://medium.com/@onlinemsr)