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:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

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