• Post category:JavaScript
  • Reading time:4 mins read

In this article, we will explain to you how to compare two dates in JavaScript and give you a simple guide that will help you to get the results as you expected.

To compare the values of two dates, we need to check the first date is greater, less or equal than the second date. Using the Date object we can compare dates in JavaScript.

Different ways to compare two dates in JavaScript

  1. Compare two dates without time
  2. Compare dates with time
  3. Compare dates using getTime() function

1. Compare two dates without time

Here, we will learn to compare dates using new Date() operators that creates a new date object with the current date and time. Assume that, we have two JavaScript Date objects like:

var date1 = new Date("2018-04-17");
var date2 = new Date("2019-03-28");

if (date1 > date2) {
  console.log("date1 is greater than date2");
} else if (date1<date2) {
   console.log("date1 is less than date2");
} else {
  console.log("date1 is equal to date2");
}

// Output: date1 is less than date2

2. Compare dates with time

Let’s see another example to compare dates with time.

var date1 = new Date("Apr 17, 2018 19:15:50");
var date2 = new Date("Mar 28, 2019 18:36:41");

if (date1 > date2) {
  console.log("date1 is greater than date2");
} else if (date1 < date2) {
   console.log("date1 is less than date2");
} else {
  console.log("date1 is equal to date2");
}

// Output: date1 is less than date2

3. Compare dates using getTime() function

Now we’ll see the example to compare dates using getTime() function that returns the number of milliseconds.

We recommend that, comparing dates using getTime() function is good practice instead of comparing dates using new date() operator. Here we compare the date with current date.

var currentDate = new Date();
var date = new Date("Mar 28, 2019 18:36:41");

if (currentDate.getTime() > date.getTime()) {
  console.log("currentDate is greater than date");
} else if (currentDate.getTime() < date.getTime()) {
   console.log("currentDate is less than date");
} else {
  console.log("currentDate is equal to date");
}

// Output: currentDate is greater than date

Thank you for reading! Happy Coding..!!

Leave a Reply