OneBite.Dev - Coding blog in a bite size

compare dates in javascript

Code snippet for how to how to compare dates in javascript with sample and detail explanation

Comparing dates in JavaScript is an essential task that often arises in web development. This article is designed to provide a simple comprehension of how to carry out this operation using straightforward and easily understandable examples.

Code snippet: Comparing Dates in JavaScript

const date1 = new Date('2020-12-17T03:24:00');
const date2 = new Date('2021-01-15T03:24:00');

if(date1 < date2) {
  console.log("date1 is less than date2");
} else if(date1 > date2) {
  console.log("date1 is more than date2");
} else {
console.log("dates are equal");
}

Code Explanation for Comparing Dates in JavaScript

In the provided JavaScript code, we’re comparing two dates to see if one is greater, less or equal to the other. Below is a step-by-step breakdown of how this works:

  1. First of all, we declare two constants named date1 and date2 using the new Date() constructor. The Date() constructor creates a new date object with the date and time defined as a string (‘YYYY-MM-DDTHH:MM:SS’).
const date1 = new Date('2020-12-17T03:24:00');
const date2 = new Date('2021-01-15T03:24:00');
  1. Next, we use an if statement to check if date1 is less than date2. If it is, the message “date1 is less than date2” will be printed in the console.
if(date1 < date2) {
  console.log("date1 is less than date2");
}
  1. We use an else-if statement next to check if date1 is greater than date2. If this is true, then “date1 is more than date2” will be logged to the console.
else if(date1 > date2) {
  console.log("date1 is more than date2");
} 
  1. Lastly, if neither of the above conditions are met, it means that both dates are equal and consequently the message “dates are equal” will be printed to the console.
else {
  console.log("dates are equal");
}

This way, you can easily compare two dates in JavaScript. Remember, when comparing dates the JavaScript’s Date object does the heavy lifting, converting date strings into date-time representations that can be objectively compared. This is a basic example and can be tailored to suit specific requirement in applications.

javascript