Compare Dates in JavaScript

Leave a comment

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:

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, BI, Web, Cloud and Data Science.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

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