Blog / Javascript

How to compare two dates in JavaScript

How to compare two dates in JavaScript

Find out how to compare two dates in JavaScript, with and without time, with and without libraries like date-fns.

Will MaygerWill Mayger
August 12, 2021
Article

In this post we will be covering how to compare two dates in JavaScript with as little technical jargon as possible so you will have everything you need right here without having to look any further!

Comparing dates is something that can be a little confusing in JavaScript because you can’t just compare two Date objects because they are objects and as well all know {} !== {}.

There are many different scenarios to comparing dates in JS, such as if you want to compare whole dates, days, hours, months, years, with or without time, the current date, and so on.

On top of equality comparisons, we will also probably want to be able to perform greater than or equal comparisons with dates in JavaScript as well.

As well as our own comparisons, there are many libraries out there as well.

In this post we will be covering all of these topics!

Comparing two JavaScript dates

Firstly to compare two dates in JavaScript, let’s take a look at how we can compare two dates to see if they are equal.

In JavaScript, it is well known that we cannot compare two different objects, even if they are the same because they are different instances which means they will always fail when comparing them.

With this in mind, we can’t just compare two Date Objects with a comparison operator because they are also objects.

const dateOne = new Date("25/12/2021")
const dateTwo = new Date("25/12/2021")

dateOne === dateTwo // false
dateOne === dateOne // true
dateTwo === dateTwo // true

Instead we need to get the value from the Date objects before we can compare them and there are a few different ways to do this.

The main option we can use when comparing dates is to use Date.prototype.getTime(). The Date.prototype.getTime() method will return the time in milliseconds since the Unix epoch.

What this means is we get a quantifiable number that we can use to compare, or even use greater than or equal to operators with.

Here is an example of how this will look:

const dateOne = new Date("25/12/2021")
const dateTwo = new Date("25/12/2012")

dateOne.getTime() === dateTwo.getTime() // false
dateOne.getTime() >= dateTwo.getTime() // true
dateOne.getTime() < dateTwo.getTime() // false

const dateThree = new Date("25/12/2021")

dateOne.getTime() === dateThree.getTime() // true

One note here, if you are just doing an exact comparison, you can even use .toString() to compare the dates like so:

dateOne.toString() === dateTwo.toString() // false
dateOne.toString() === dateThree.toString() // true

Compare two dates in JavaScript by days, months, or years in JavaScript (without time)

So, what do I mean here by comparing dates by days, months, or years without time?

Well whilst in most cases a simple comparison will suffice, we might also need to check if two dates are the same day, month or year without time.

When I say comparing dates without time here, I mean literally without the time part of a date, which just means we need to look at years, months and days, and not hours, minutes, seconds, and milliseconds.

For example, we might want to check if a Date is before, on, or after a certain day, and if we use a comparison using milliseconds like above whilst still accounting for the time part of the date, we would be checking the milliseconds of the hours, minutes, seconds, and milliseconds as well which means we won’t be comparing only the days.

This means that we would potentially have failed comparisons that should have passed because time is too granular for what we need when comparing days.

To solve this problem there are many solutions so it is very much a case of selecting which one you prefer or suits your situation the best.

One of the simplest solutions, and the one we will cover in this post, to understand is to once again use the getTime method just like before so that we are still working with a single number, but before we perform the comparison, we can first set the hours, minutes, seconds, and milliseconds to 0 on all dates to remove the time from the dates so that we create an even playing field so we can compare only what we need.

The best way to do this is if we create a helper function, let’s take a look at how we can compare days like this:

const compareDays = (dateOne, dateTwo) => {
  const dateA = new Date(
    dateOne.getYear(),
    dateOne.getMonth(),
    dateOne.getDay()
  )
  const dateB = new Date(
    dateTwo.getYear(),
    dateTwo.getMonth(),
    dateTwo.getDay()
  )

  if (dateA.getTime() > dateB.getTime()) {
    return 1
  }

  if (dateA.getTime() < dateB.getTime()) {
    return -1
  }

  return 0
}

In this helper function we create two new dates and we only set the years, months and days, and not the hours, minutes, seconds and milliseconds.

By doing that we can compare only the days without the time. To compare seconds, hours, months or years it is the exact same principle but you just need to pass in whichever is relevant into the Date constructor for your needs.

With months for example, you would only need to pass in years and months, whereas for years you would only need to pass in years, but for hours you would need to pass in the years, months, days and hours.

The last part to look at with this helper function is that it will return 0 if the dates are equal, 1 if the first date is larger than the second date, and -1 if the first date is less than the second date.

Whilst this is fine in this case, it would be better to split this up into multiple, more verbose, helper functions to avoid confusion, we can do this like so:

const getDateAsDay = someDate =>
  new Date(someDate.getYear(), someDate.getMonth(), someDate.getDay())

const datesAreEqual = (dateA, dateB) =>
  getDateAsDay(dateA).getTime() === getDateAsDay(dateB).getTime()

const dateIsAfter = (dateA, dateB) =>
  getDateAsDay(dateA).getTime() > getDateAsDay(dateB).getTime()

const dateIsBefore = (dateA, dateB) =>
  getDateAsDay(dateA).getTime() < getDateAsDay(dateB).getTime()

By splitting these out into individual functions it makes it easier to read, use and maintain in the future and we now get the added benefit of dealing with booleans rather than numbers.

How can we improve comparing two dates in JavaScript with a library

These methods of comparing dates will work for the current time, preset times and times in any format (e.g mm/dd/yyyy) as long as they have been created as a native JavaScript Date.

This is great if you are wanting your comparisons to be as lightweight as possible, but the problem is that it can be pretty time consuming to have to write out and test all the helper methods you might need to compare and work with JavaScript dates.

This is where a good, lightweight library could save you a lot of time, and headaches.

One of the best JavaScript date libraries out there for this problem is called date-fns.

Unlike something like moment.js (which is to be avoided), date-fns uses the native JavaScript Date object so you don’t have to worry about having a large overhead in the size of the library.

Also, date-fns is simply a collection of utilities and helper methods to make using native JavaScript Date objects much easier, similar to what we did above.

To compare two dates with date-fns, all you need to do is to import the functions, isAfter, isBefore, or areEqual to get the same functionality as above.

Or if you want to compare days you can just import isSameDay.

If you want to read their documentation to find out more helper methods you can find it here.

Here are a few examples using date-fns to compare two dates in JavaScript:

import { isAfter, isBefore, areEqual, isSameDay } from "date-fns"

const dateOne = new Date("25/12/2021")
const dateTwo = new Date("25/12/2012")

isAfter(dateOne, dateTwo) // true
isBefore(dateOne, dateTwo) // false
areEqual(dateOne, dateTwo) // false
isSameDay(dateOne, dateTwo) // false

Summary

There we have how to compare two dates in JavaScript, if you want more like this be sure to check out some of my other posts!

Foxi - Budget Planner & Tracker

Foxi

Budget Planner & Tracker

More money in your pocket by the end of the month.

Free to use and no account needed.

Get started now.

Get the app

Some graphics used on this post were made using icons from flaticon.

Latest Posts

Learn React, JavaScript and TypeScript

Learn React, JavaScript and TypeScript

Join the platform that top tier companies are using.
Master the skills you need to succeed as a software engineer and take your career to the next level with Pluralsight.

Start here

Become an expert in ReactJS, TypeScript, and JavaScript.

Here you will find my personal recomendations to you, for full disclosure I earn a small commission from some of these links, but I only recommend what I trust and personally use.

Good things are coming, don't miss out!

Good things are coming, don't miss out!

Follow me on Twitter to stay up to date and learn frontend, React, JavaScript, and TypeScript tips and tricks!

Are you a novice, intermediate or expert react engineer?

Find out here by taking my fun, interactive, quick quiz which takes approximately 1 - 3 minutes. How well will you will do?

Foxi - Budget Planner & Tracker

Foxi

Budget Planner & Tracker

More money in your pocket by the end of the month.

Free to use and no account needed.

Get started now.

Get the app