Categories
JavaScript Answers

How to Determine Date Equality in JavaScript?

Spread the love

To determine date equality with JavaScript, we can convert both dates to timestamps with the getTime method.

Then we can compare them directly since timestamps are integers.

For instance, we can write:

const d1 = new Date(2021, 1, 1)  
const d2 = new Date(2021, 1, 1)  
console.log(d1.getTime() === d2.getTime())

To create 2 dates d1 and d2 with the Date constructor.

We pass in the year, month, and day into the Date constructor to create the JavaScript date objects.

Then we call getTime on each to compare them directly as timestamps.

Therefore, the console log should log true since they are the same dates.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.