Coders Packet

Compare Two Dates in JavaScript

By Harsh Tanwar

Today we will learn How to compare two dates. We compare if a date is after or before another, if the date is today, how many days there are between dates

Date Object in Javascript

As the modern web evolved, JavaScript introduced a new object constructor called Date to handle date-time operations.

This means that you don't need an external library to perform rudimentary checks and operations, which makes it easier to perform these things in Vanilla JS.

Even though this implementation seems a bit simplistic, the addition of the Date class was quite a big improvement, since there was finally a level of abstraction between developers and raw dates.

 

Now, let's look at different ways to compare two dates using Date objects.

Comparing Two Dates in JavaScript

We can use comparison operators like < and > two compare two Date objects, and under the hood, their time counters are effectively compared. You're effectively comparing two integer counters

 

/* Comparing two dates in Javascript */

/* Function to compare dates */
function dateCompare(d1, d2) {
  const date1 = new Date(d1); /* date 1 */
  const date2 = new Date(d2); /* date 2 */

  /* If - Else conditions used */
  if (date1 > date2) {
    console.log(`${d1} is greater than ${d2}`);
  } else if (date1 < date2) {
    console.log(`${d2} is greater than ${d1}`);
  } else {
    console.log(`Both dates are equal`);
  }
}
/* Print the obtained Data */
console.log(1);
dateCompare("9/2/2000", "9/2/2021");
console.log(2);
dateCompare("10/5/2021", "10/6/2021");
console.log(3);
dateCompare("01/01/2022", "01/01/2022");

Output - 

1
9/2/2021 is greater than 9/2/2000
2
10/6/2021 is greater than 10/5/2021
3
Both dates are equal

As we can see, comparing dates just boils down to converting the provided strings into Date objects and comparing them with an appropriate comparison operator.

Download project

Reviews Report

Submitted by Harsh Tanwar (harshtanwar)

Download packets of source code on Coders Packet