Borislav Hadzhiev
Mon Jan 24 2022·2 min read
Photo by Henri Pham
To check if two dates are equal:
getTime()
method to get a timestamp of each date.const date1 = new Date('2022-09-24'); const date2 = new Date('2022-09-24'); // ✅ Check if two dates have same date AND time components if (date1.getTime() === date2.getTime()) { console.log('✅ Dates have same date AND time components'); } // ✅ Check if two dates have same date components if (date1.toDateString() === date2.toDateString()) { console.log('✅ Dates have same date components'); }
The getTime() method returns the number of milliseconds elapsed between the 1st of January 1970 and the given date.
const date1 = new Date('2022-09-24'); // 👇️ 1663977600000 console.log(date1.getTime());
If you only need to check if two dates have the same year, month and day, you
can use the toDateString()
method.
const date1 = new Date('2022-09-24'); const date2 = new Date('2022-09-24'); // ✅ Check if two dates have same date components if (date1.toDateString() === date2.toDateString()) { console.log('✅ Dates have same date components'); }
The
toDateString
method returns a string representation of the date portion of the given Date
object in a human-readable format.
const date1 = new Date('2022-09-24'); // 👇️ "Sat Sep 24 2022" console.log(date1.toDateString());
You could also use a more manual approach and use some of the built-in methods
on the Date
object.
const date1 = new Date('2022-09-24'); const date2 = new Date('2022-09-24'); if ( date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate() ) { console.log('dates have same year, month and day'); }
This is a more explicit approach to achieve the same goal.
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.
You could use the same approach to compare the hours, minutes and seconds.
const date1 = new Date('2022-09-24'); const date2 = new Date('2022-09-24'); if ( date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate() && date1.getHours() === date2.getHours() && date1.getMinutes() === date2.getMinutes() && date1.getSeconds() === date1.getSeconds() ) { console.log('✅ dates have same date and time components'); }
We used the following 3 time-related methods:
Date.getHours - returns the hour for the specified date.
Date.getMinutes - returns the minutes for a date.
Date.getSeconds - returns the seconds of a specific date.
When the logical AND (&&) operator is used, all of the conditions have to be met
for the if
block to run.