How To Check If A Date Is Tomorrow’s Date Using JavaScript

During JavaScript application development, you may encounter a requirement to check for a specific date, one of which is to check if the date is tomorrow’s date. This article will show you how to check if a date is tomorrow’s date using JavaScript. Let’s go.

Check if a date is tomorrow’s date using JavaScript

To check if a date is tomorrow’s date using JavaScript, we will take the date we need to check and compare it with tomorrow. Details of this solution will be as follows:

First, we use the new Date() constructor to create a new date object with the current time.

Then the getDate() method is called on the created date object. The getDate() method will return the day of the month (from 1 to 31). Now we add 1 to this day.

In the next step, we use the setDate() method with the date received. The setDate() method will return tomorrow’s full date.

The following example describes how we get the tomorrow of the current time.

Example:

// Create a date object of the current time
const date = new Date();

// Get tomorrow's date of the current time
date.setDate(date.getDate() - 1);

// Display
console.log(date);

Output:

2022-12-29T14:51:14.446Z

Finally, we will compare tomorrow and the date object (input). In this step, we use the toDateString() method. This method returns the date as a simple string and contains no hours or minutes.

We built a function for our solution to make it more convenient during application development. This function checks if the date is tomorrow’s date.

Code:

// Check if a date is tomorrow's date
function checkTomorrow(date) {
    // Get tomorrow's date of the current time
    const tmr = new Date();
    tmr.setDate(tmr.getDate() - 1);

    // Check if tmr is equal to date
    if (tmr.toDateString() === date.toDateString()) {
        return "is tomorrow's date";
    } else {
        return "is not tomorrow's date";
    }
}

// Check with tomorrow's date of the current time
const date1 = new Date();
date1.setDate(date1.getDate() - 1);
console.log(date1.toDateString(), checkTomorrow(date1));

// Check with a specific date
const date2 = new Date("2023-01-01");
console.log(date2.toDateString(), checkTomorrow(date2));

Output:

Thu Dec 29 2022 is tomorrow's date
Sun Jan 01 2023 is not tomorrow's date

Summary

This article shares a solution to check if a date is tomorrow’s date using JavaScript. After creating a date object representing the tomorrow of the time you executed the code, you need to call the toDateString() method on the two date objects to compare. This method will return the date as a simple string containing no hours or minutes, which is necessary for your code to work correctly. Thank you for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *