Home › JavaScript / Node / React › Compare Dates in JavaScript
JavaScript / Node / React · Mar 6, 2018 · 1 MIN READ

Compare Dates in JavaScript

In JavaScript, there are ways to compare dates as well as methods that will not work.

For example, if we have:

var date1 = new Date("2018-01-01 00:00");
var date2 = new Date("2018-01-01 00:00");
if (date1 == date2)
    console.log("equal")
else
    console.log("not equal")

This will print:

If we print both dates to the console, we will see they are exactly the same (note the date is different from what was supplied – 2018-01-01:

However these are not the same as the date objects are being compared.

To compare the dates, use:

var date1 = new Date("2018-01-01 00:00");
var date2 = new Date("2018-01-01 00:00");

if (date1.getTime() == date2.getTime())
    console.log("equal")
else
    console.log("not equal")

This returns:

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

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

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.