How to Check If A Date Is Before Another Date Using JavaScript

During application development in JavaScript language, you will encounter a requirement to check if a date is before another. For example, check if one person is older than another person. This article will share how to check if a date is before another date using JavaScript.

How to check if a date is before another date using JavaScript

Here are the steps we take to check if a date is before another date using JavaScript:

First, we initialize two date objects for comparison using the new Date() method. These date objects can be the date of birth, expiry date, etc. Click here to learn more about the new Date() method and the arguments passed to it.

We will then use the > operator to check if one of the two date objects is less than the other. The < operator is a helpful comparison operator in JavaScript. The < operator is used to check if one value is less than another.

When we compare two date objects, the valueOf() method is automatically called internally and converts these date objects to primitive values (number of milliseconds since January 1, 1970, 00:00:00.). The date object with the smaller number of milliseconds will be before the remaining date object.

The following simple example will detail how this solution works:

// Create two date object
const date1 = new Date("04/29/2022");
const date2 = new Date("12/16/2022");

// Check if the 'date1' date is before the 'date2' date using the < operator
console.log(date1 < date2);



We have built a function that checks a product’s expiration date using the < operator. If the product’s expiration date is before the current time, the product can still be used.


// Create the list of products
const proList = [
    proName: 'Cookies',
    madeBy: 'LearnShareIT',
    expDate: "2022/12/25 04:25:30 PM"
    proName: 'Bread',
    madeBy: 'LearnShareIT',
    expDate: "2023/02/10 06:26:15 PM"
    proName: 'Cake',
    madeBy: 'LearnShareIT',
    expDate: "2023/01/03 11:44:50 AM"

// Checks a product's expiration date using the < operator
for (let i = 0; i < proList.length; i++) {
  // The current date
  const current = new Date();

  const exp = new Date(proList[i].expDate);

  if (current < exp) {
    console.log("The " + proList[i].proName + " product still has an expiry date")
  else {
    console.log("The " + proList[i].proName + " product has expired")


The Cookies product has expired
The Bread product still has an expiry date
The Cake product still has an expiry date


To check if a date is before another using JavaScript, you can compare two objects directly using the < comparison operator. Apply this to your program effectively. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *