Compare two dates using JavaScript

Comparing two dates in JavaScript involves converting them to Date objects and using comparison operators or methods like getTime(). We compare dates to determine chronological order, check event timings, validate date ranges, or manage scheduling in applications.

In JavaScript, use getTime() to convert dates to numeric values for direct comparison.

Example 1: This example illustrates the comparison of the dates using the getTime() function.

javascript
// Current Date
let g1 = new Date();
let g2 = new Date();
if (g1.getTime() === g2.getTime())
    console.log("Both  are equal");
else
    console.log("Not equal");

Output
Both  are equal

Example 2: This example illustrates the comparison of the current date with the assigned date using the getTime() function.

Javascript
let g1 = new Date();

// (YYYY-MM-DD)
let g2 = new Date("2019-08-03");
if (g1.getTime() < g2.getTime())
    console.log("g1 is lesser than g2");
else if (g1.getTime() > g2.getTime())
    console.log("g1 is greater than g2");
else
    console.log("both are equal");

Output
g1 is greater than g2

Example 3: This example illustrates the comparison of 2 given dates using the getTime() function.

Javascript
let g1 = new Date("2019, 08, 03, 11, 45, 55");

// (YYYY, MM, DD, Hr, Min, Sec)
let g2 = new Date("2019, 08, 03, 10, 22, 42");
if (g1.getTime() < g2.getTime())
    console.log("g1 is lesser than g2");
else if (g1.getTime() > g2.getTime())
    console.log("g1 is greater than g2");
else
    console.log("both are equal");

Output
both are equal

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.


Contact Us