How to compare Dates in JavaScript and TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 29, 2024
5 min

banner

# Table of Contents

  1. Compare two Date strings in JavaScript and TypeScript
  2. Compare Dates without Time in JavaScript and TypeScript

# Compare two Date strings in JavaScript and TypeScript

To compare two dates:

  1. Pass the strings to the Date() constructor to create 2 Date objects.
  2. Compare the output from calling the getTime() method on the dates.
index.js
const dateStr1 = '2022-04-24'; const dateStr2 = '2022-09-21'; const date1 = new Date(dateStr1); const date2 = new Date(dateStr2); if (date1.getTime() === date2.getTime()) { console.log('dates are the same'); } else { // โœ… This runs ๐Ÿ‘‡๏ธ (dates are NOT the same) console.log('dates are not the same'); } if (date1.getTime() > date2.getTime()) { console.log('date1 comes after date2'); } else if (date1.getTime() < date2.getTime()) { // โœ… This runs ๐Ÿ‘‡๏ธ (date2 comes after) console.log('date2 comes after date1'); } else { console.log('dates are the same'); }

compare two date strings

The code for this article is available on GitHub

We passed the date strings to the Date() constructor to create 2 Date objects.

If passing the date string to the Date() constructor doesn't return a valid date, then you have to format your date strings differently, e.g. YYYY-MM-DD (more on that below).

The getTime method returns a timestamp of the elapsed milliseconds between the 1st of January 1970 00:00:00 and the given date.

A greater number means that more time has passed since the Unix Epoch, therefore the date is greater.

We compared 2 dates - the 24th of April, 2022 and the 21st of September 2022.

In our first if statement, we check if the date strings point to the same year, month and day of the month, which is not the case, so our else block runs.

In the second example, the else if block runs because the second date comes after the first.

# Comparing two date strings implicitly

It should be noted that you don't have to explicitly call the getTime() method when comparing the dates.

index.js
const dateStr1 = '2022-04-24'; const dateStr2 = '2022-09-21'; const date1 = new Date(dateStr1); const date2 = new Date(dateStr2); if (date1 > date2) { console.log('date1 comes after date2'); } else if (date1 < date2) { // โœ… This runs ๐Ÿ‘‡๏ธ (date2 comes after) console.log('date2 comes after date1'); } else { console.log('dates are the same'); }

comparing two date strings implicitly

The code for this article is available on GitHub
Each date stores a timestamp under the hood, so the default behavior is to compare the timestamps of the dates even if you don't explicitly call the getTime() method on each date.

Which approach you pick is a matter of personal preference.

I've also written a detailed article on how to convert a string to a Date object in TS.

# Formatting the two Date strings properly

If you have difficulties creating a valid Date object from your date strings, you can pass 2 types of parameters to the Date() constructor:

  1. a valid ISO 8601 string, formatted as YYYY-MM-DDTHH:mm:ss.sssZ, or just YYYY-MM-DD, if you only have a date without time.
  2. multiple, comma-separated parameters that represent the year, month (0 = January to 11 = December), day of the month, hours, minutes and seconds.

Here is an example that splits a string and passes the parameters to the Date() constructor to create a Date object.

index.js
// ๐Ÿ‘‡๏ธ Formatted as MM/DD/YYYY const str = '07/21/2022'; const [month, day, year] = str.split('/'); // ๐Ÿ‘‡๏ธ Create valid Date object const date = new Date(+year, +month - 1, +day); console.log(date); // ๐Ÿ‘‰๏ธ Thu Jul 21 2022
The code for this article is available on GitHub

The date string is formatted as mm/dd/yyyy, but the approach applies to any other format.

We split the string on each forward slash to get an array of substrings.

index.js
const str = '07/21/2022'; // ๐Ÿ‘‡๏ธ ['07', '21', '2022'] console.log(str.split('/'))

We used array destructuring to assign the month, day and year values to variables and passed them to the Date() constructor.

Once the Date object is created, all you have to do to compare the dates is compare the output from their getTime methods.

index.js
const str = '07/21/2022'; // ๐Ÿ‘‡๏ธ ['07', '21', '2022'] console.log(str.split('/')); const [month, day, year] = str.split('/'); // ๐Ÿ‘‡๏ธ Create valid Date object const date = new Date(+year, +month - 1, +day); console.log(date); // ๐Ÿ‘‰๏ธ Thu Jul 21 2022 const now = new Date(); if (date.getTime() > now.getTime()) { console.log('date is in the future'); }

Notice that we subtracted 1 from the month when passing it to the Date() constructor.

This is because, the Date constructor expects a zero-based value, where January = 0, February = 1, March = 2, etc.

I've also written a detailed guide on how to format date/time in TS.

# Compare Dates without Time in JavaScript and TypeScript

To compare dates without time:

  1. Create a copy of each date.
  2. Use the setUTCHours() method to set the time on the copied dates to midnight.
  3. Compare the output from calling the getTime() method on the dates.
index.js
const date1 = new Date('2022-01-23T06:55:31.820Z'); const date2 = new Date('2022-01-23T09:30:24.820Z'); const date1WithoutTime = new Date(date1.getTime()); const date2WithoutTime = new Date(date2.getTime()); date1WithoutTime.setUTCHours(0, 0, 0, 0); date2WithoutTime.setUTCHours(0, 0, 0, 0); if (date1WithoutTime.getTime() === date2WithoutTime.getTime()) { // โœ… This runs ๐Ÿ‘‡๏ธ (dates are the same) console.log('dates are the same'); } else { console.log('dates are not the same'); } if (date1WithoutTime.getTime() > date2WithoutTime.getTime()) { console.log('date1 comes after date2'); } else if (date1WithoutTime.getTime() === date2WithoutTime.getTime()) { // โœ… This runs ๐Ÿ‘‡๏ธ (dates are the same) console.log('date1 and date2 are the same'); } else { console.log('date2 comes after date1'); }

compare dates without time

The code for this article is available on GitHub

We used the Date() constructor to create 2 Date objects that both store the 23rd of January 2022.

To be able to compare the dates and ignore the time, we have to reset the time of the dates to Midnight (or simply the same hour, minutes, seconds and milliseconds).

The setUTCHours method takes the hours, minutes, seconds and milliseconds as parameters and sets the values on the given date according to Universal Time.

index.js
const date1 = new Date('2022-01-23T06:55:31.820Z'); const date2 = new Date('2022-01-23T09:30:24.820Z'); const date1WithoutTime = new Date(date1.getTime()); const date2WithoutTime = new Date(date2.getTime()); date1WithoutTime.setUTCHours(0, 0, 0, 0); date2WithoutTime.setUTCHours(0, 0, 0, 0);
However, the setUTCHours method mutates the Date object in place, which might not be what you want.

This is why we used the getTime method to get a timestamp of the elapsed milliseconds between the 1st of January 1970 00:00:00 and the given date.

We can pass the timestamp to the Date() constructor to create a copy of the Date object.

We used the setUTCHours method to set the time for the dates to midnight, so we could compare the dates ignoring the time.

The getTime method returns a number that represents the milliseconds elapsed between the Unix Epoch and the given date.

index.js
// ๐Ÿ‘‡๏ธ 1642944933161 console.log(new Date().getTime());

If we have two dates that store the same year, month and day of the month, then the timestamps are going to be equal because we set the time on both dates to midnight.

If one date is greater than another, then its timestamp is going to store a larger number because more time has elapsed between the Unix Epoch and the specific date.

You can compare the output from getTime() just like you would compare numbers in JavaScript.

Here is an example where date1 stores the 23rd of February 2022 and date2 stores the 27th of April 2022.

index.js
const date1 = new Date('2022-02-23T06:55:31.820Z'); const date2 = new Date('2022-04-27T09:30:24.820Z'); const date1WithoutTime = new Date(date1.getTime()); const date2WithoutTime = new Date(date2.getTime()); date1WithoutTime.setUTCHours(0, 0, 0, 0); date2WithoutTime.setUTCHours(0, 0, 0, 0); if (date1WithoutTime.getTime() === date2WithoutTime.getTime()) { console.log('dates are the same'); } else { // โœ… This runs ๐Ÿ‘‡๏ธ (dates are NOT the same) console.log('dates are not the same'); } if (date1WithoutTime.getTime() > date2WithoutTime.getTime()) { console.log('date1 comes after date2'); } else if (date1WithoutTime.getTime() === date2WithoutTime.getTime()) { console.log('date1 and date2 are the same'); } else { // โœ… This runs ๐Ÿ‘‡๏ธ (date2 comes after date1) console.log('date2 comes after date1'); }

The value in the date2 variable comes after the one in the date1 variable, therefore its timestamp is a greater number, so the else statement runs in both conditionals.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev