Check If A Date Is Tomorrow’s Date Using JavaScript

To check if a date is tomorrow’s date using JavaScript –

  1. Use the Date constructor to get the current date.
  2. Add 1 to the current date to get tomorrow’s date.
  3. Use toDateString() method to compare the date with tomorrow’s date.
  4. If the two dates are equal, then it is tomorrow’s date.
check if a date is tomorrow's date using javascript

Check If A Date Is Tomorrow’s Date Using JavaScript

Let’s create a reusable function to check if a date is tomorrow’s date using JavaScript.

function isTomorrow(date) {

  const tomorrow = new Date();

  tomorrow.setDate(tomorrow.getDate() + 1);

  return date.toDateString() === tomorrow.toDateString();

}

console.log(isTomorrow(new Date())); //false

console.log(isTomorrow(new Date("June 07, 2022"))); //true

In the above code, we first created a Date object named tomorrow and set tomorrow’s date by adding 1 to the current date.

Then we compared the date with tomorrow’s date using the toDateString() method. If the two dates are equal, then it is tomorrow’s date.

The toDateString() method converts the date to a string in the format “Day Month Date, Year”.

console.log(new Date().toDateString()); //Mon Jun 06 2022

console.log(new Date("June 07, 2022").toDateString()); //Tue Jun 07 2022

If we compare a date with another date using ===, then it will compare the dates by their value and by reference.

But if we use the toDateString() method, then it will convert the dates to strings and compare them.

For example,

let date1 = new Date("June 07, 2022");

let date2 = new Date("June 07, 2022");

console.log(date1 === date2); //false

console.log(date1.toDateString() === date2.toDateString()); //true

In the above code, we created two dates with the same value but they are not equal by reference because they are two different objects.

But when we compare them using toDateString() method, they are equal by value and return true.

It is important that we ignore the hours, minutes, and seconds when we compare dates because the day changes at midnight.

For example,

console.log(isTomorrow(new Date("June 06, 2022 23:59:59"))); //false

In the above code, we created a date with June 06, 2022, 23:59:59. But since it is not midnight, the day is still considered as today and not tomorrow.

Therefore it returns false.

So, the isTomorrow() function will return true if the date passed to it is tomorrow’s date.

Otherwise, it will return false.

You can use this function to check if a date is tomorrow’s date using JavaScript.

Leave a Reply