Borislav Hadzhiev
Mon Jan 24 2022·2 min read
Photo by Meiying Ng
To check if two dates are the same day:
getFullYear()
method for the two dates.getMonth()
and getDate()
methods.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. Yes, 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.
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.
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.
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.