Borislav Hadzhiev
Tue Jan 25 2022·2 min read
Photo by Farsai Chaikulngamdee
To check if a date is tomorrow's date:
1
day to the current date to get tomorrow's date.toDateString()
method to compare the dates.2
equal strings, the date is tomorrow's date.function isTomorrow(date) { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); // 👇️ Tomorrow's date console.log(tomorrow); if (tomorrow.toDateString() === date.toDateString()) { return true; } return false; } const t = new Date(); t.setDate(t.getDate() + 1); console.log(isTomorrow(t)); // 👉️ false console.log(isTomorrow(new Date('2022-01-21'))); // 👉️ false
We created a reusable function that takes a Date
object as a parameter and
check if the passed in date is tomorrow.
The first thing we did in the function is use the Date() constructor to get the current date.
Once we have the current date, we have to add 1
day to it to get tomorrow's
date.
The
setDate()
method takes a number that represents the day of the month and sets the value on
the given Date
instance.
Date
object in JavaScript automatically handles the scenario where adding X days to the date pushes us into the next month or year and adjusts the values.Now that we have tomorrow's date, all we have to do is compare the date to 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 tomorrow's date and the passed in date, then the passed in date is tomorrow's date.