Check if two Dates are the same Day in JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 25, 2022

banner

Photo from Unsplash

Check if two Dates are the same Day in JavaScript #

To check if two dates are the same day:

  1. Compare the output from the getFullYear() method for the two dates.
  2. Do the same for the output of the getMonth() and getDate() methods.
  3. If the conditions are met, the dates are the same day.
index.js
const date1 = new Date('2022-06-19'); const date2 = new Date('2022-06-19'); if ( date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate() ) { console.log('✅ dates are the same day'); } else { console.log('⛔️ dates are not the same day'); }

We used the following 3 date-related methods:

  • Date.getFullYear method - returns a four-digit number representing the year that corresponds to a date.

  • Date.getMonth - returns an integer between 0 (January) and 11 (December) and represents the month for a given date. Unfortunately, the getMonth method is off by 1.

  • Date.getDate - returns an integer between 1 and 31 representing the day of the month for a specific date.

We used the logical AND (&&) operator, which means that for our if block to run, all of the conditions have to be met.

index.js
const date1 = new Date('2022-06-19'); const date2 = new Date('2022-06-19'); if ( date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate() ) { console.log('✅ dates are the same day'); } else { console.log('⛔️ dates are not the same day'); }
If the dates have the same year, month and day of the month, then they are the same day.

Alternatively, you can use the toDateString method.

To check if two dates are the same day, call the toDateString() method on both Date() objects and compare the results. If the output from calling the method is the same, the dates are the same day.

index.js
const date1 = new Date('2022-06-19'); const date2 = new Date('2022-06-19'); if (date1.toDateString() === date2.toDateString()) { console.log('✅ dates are the same day'); } else { console.log('⛔️ dates are not the same day'); }

The toDateString() method returns a string that represents the date portion of the given Date object in human-readable form.

index.js
const date1 = new Date('2022-06-19'); // 👇️ Sun Jun 19 2022 console.log(date1.toDateString());

If calling the method on both Date objects returns two equal strings, then the dates are the same day.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.