Borislav Hadzhiev
Tue Jan 25 2022·2 min read
Photo by Farsai Chaikulngamdee
To check if a date is today's date:
Date()
constructor to get today's date.toDateString()
method to compare the two dates.2
equal strings, the date is today's date.function isToday(date) { const today = new Date(); // 👇️ Today's date console.log(today); if (today.toDateString() === date.toDateString()) { return true; } return false; } console.log(isToday(new Date())); // 👉️ true console.log(isToday(new Date('2022-01-21'))); // 👉️ false
We used the Date() constructor to get the current date.
The next step is to compare the current date with the passed in date, ignoring the time.
The
toDateString
method returns the date portion of a Date
object in human-readable form.
// 👇️ Tue Jan 25 2022 console.log(new Date().toDateString());
If the method returns the same string for the current date and the passed in date, then the passed in date is today's date.
Alternative, you could use a more explicit approach.
To check if a date is today's date:
Date()
constructor to get today's date.getFullYear()
, getMonth()
and getDate()
methods for the dates.function isToday(date) { const today = new Date(); // 👇️ Today's date console.log(today); if ( today.getFullYear() === date.getFullYear() && today.getMonth() === date.getMonth() && today.getDate() === date.getDate() ) { return true; } return false; } console.log(isToday(new Date())); // 👉️ true console.log(isToday(new Date('2022-01-21'))); // 👉️ false
The function makes use of 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.
If the year, month and day of the month values for the current date are equal to the values for the passed in date, then the date is today's date.
toDateString
method, as it is more concise and just as readable.