Code recipe: How to compare dates in JavaScript

Posted on February 18, 2021


As you code your JavaScript application, you may find that you need to compare the values of two dates in order to see if one of them is greater or less than the other.

The simplest way to compare different dates is to first convert them to a Date object using the new Date() construct. Most of the time, you will get a date value out of a date picker UI. That means you can pass the string representing your date into the new Date() construct to create the Date object.

For example, let’s create two dates called myDate and yourDate, with myDate value less than yourDate:

let myDate = new Date("January 13, 2021");
let yourDate = new Date("February 13, 2021");

Once you have the dates, you can compare them using less than (<) or greater than (>) operator:

let myDate = new Date("January 13, 2021");
let yourDate = new Date("February 13, 2021");

if (myDate < yourDate) {
  console.log("myDate is less than yourDate"); // will be printed
}
if (myDate > yourDate) {
  console.log("myDate is greater than yourDate");
}

And just like that, you can find whether one date value is greater or less than the other.

Keep in mind, however, that the equality comparison operator (=== or ==) won’t work directly for these Date objects:

let myDate = new Date("January 13, 2021");
let yourDate = new Date("January 13, 2021");

if (myDate === yourDate) {
  console.log("Dates are equal");
} else {
  console.log("Dates are NOT equal"); // will be printed
}

The code above will print “Dates are NOT equal”. If you want to use the equal operator, you need to compare the dates using the getTime() method.

The getTime() method will return the milliseconds that has passed between 1 January 1970 00:00:00 UTC and the given date. You can consider the dates are equal when they return the same milliseconds:

let myDate = new Date("January 13, 2021");
let yourDate = new Date("January 13, 2021");

if (myDate.getTime() === yourDate.getTime()) {
  console.log("Dates are equal");
} else {
  console.log("Dates are NOT equal"); // will be printed
}

The code above will print “Dates are equal” to the console.

Finally, you can also pass the time of the day to the Date construct to compare the values by the time:

let myDate = new Date("January 13, 2021 12:00:00");
let yourDate = new Date("January 13, 2021 15:00:00");

if (myDate < yourDate) {
  console.log("myDate is less than yourDate"); // will be printed
}
if (myDate > yourDate) {
  console.log("myDate is greater than yourDate");
}

And that’s how you can compare dates in JavaScript. Feel free to use the code in your projects.

See also:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more