;

How to Compare Two Dates in Javascript


Tutorialsrack 11/03/2021 Javascript

In this article, you will learn how to compare two dates in javascript. Date comparison is required any time you are using Date in your code or program. You can create the new Date objects using the Date() Constructor. You can compare two dates with JavaScript, you compare them using the >, <, <= or >= operators.

This article will help you to resolve the following problems:

  1. Compare two dates with time.
  2. Compare today's date with any other date.
  3. Compare past and future dates with a given date.

Example 1: Compare Two Dates with Time in Javascript

In this example, we create two new same dates with different times.

Example 1: Compare Two Dates with Time in Javascript
// Compare two Dates with Time in Javascript
function CompareDate() {
    // create new date using Date Object => new Date(Year, Month, Date, Hr, Min, Sec);
    var firstOne = new Date(2021, 04, 20, 14, 55, 59);
    var secondTwo = new Date(2021, 04, 20, 12, 10, 20);
  
    //Note: 04 is month i.e. May
    if (firstOne > secondTwo) {
        alert("First Date is greater than Second Date.");
    } else {
        alert("Second Two is greater than First Date.");
    }
}
 
CompareDate();

Example 2: Compare Today's Date With Any Other Date in Javascript.

In this example, we create two dates, today’s date and or another one is any random date, and compare these two dates.

Example 2: Compare Today's Date With Any Other Date in Javascript.
// Compare Today's date with another Date

function CompareDate() {
    var todayDate = new Date(); //Today Date
    var anyDate = new Date(2020, 11, 25);
    if (todayDate > anyDate) {
        alert("Today's Date is greater than other given Date.");
    } else {
        alert("Today's Date is smaller than other given Date.");
    }
}
CompareDate();

Example 3: Compare Past and future dates with a given date.

In this example, we create two dates and compare these dates.

Example 3: Compare Past and future dates with a given date.
//Compare Two Dates in Javascript
function CompareDate() {
    //Note: 00 is month i.e. January
    var firstDate = new Date(2020, 3, 15); //Year, Month, Date
    var secondDate = new Date(2021, 3, 15); //Year, Month, Date
    if (firstDate > secondDate) {
        alert("First Date is greater than Second Date.");
    } else {
        alert("Second Date is greater than First Date.");
    }
}

CompareDate();

I hope this article will help you to understand how to compare two dates in javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags