W3jar
326 words
2 minutes

How to Check If a Date is Tomorrow in JavaScript

To check if a given date is tomorrow in JavaScript, you can follow these steps:

  1. Get the current date and time.
  2. Calculate what tomorrow’s date is.
  3. Compare the provided date to tomorrow’s date.

Here’s a concise example of how you can achieve this in JavaScript:

function isTomorrow(date) {
    // Ensure the provided input is a Date object
    if (!(date instanceof Date)) {
        throw new TypeError("Input must be a Date object");
    }

    // Get the current date and time
    const now = new Date();

    // Create a date object for tomorrow
    const tomorrow = new Date(now);
    tomorrow.setDate(now.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0); // Set to start of the day

    // Create a date object for the end of tomorrow
    const endOfTomorrow = new Date(tomorrow);
    endOfTomorrow.setHours(23, 59, 59, 999); // Set to end of the day

    // Normalize the input date to the start of the day for comparison
    const inputDate = new Date(date);
    inputDate.setHours(0, 0, 0, 0); // Set to start of the day

    // Check if the input date is within the range of tomorrow
    return inputDate >= tomorrow && inputDate <= endOfTomorrow;
}

// Example usage
const testDate = new Date();
testDate.setDate(testDate.getDate() + 1); // Setting testDate to tomorrow
console.log(isTomorrow(testDate)); // Should print true

Explanation:#

  1. Ensure Date Object: The function first ensures that the input is a Date object. If not, it throws an error.

  2. Get Current Date: We get the current date and time with new Date().

  3. Calculate Tomorrow: We create a new date object for tomorrow by adding one day to the current date and set its hours to midnight (start of the day).

  4. Define Date Ranges:

    • tomorrow: Start of the day tomorrow.
    • endOfTomorrow: End of the day tomorrow (23:59:59.999).
  5. Normalize Input Date: The date to be checked is normalized to the start of the day to only compare dates and ignore time.

  6. Comparison: We check if the normalized input date falls within the range of tomorrow.

This method ensures that the function will correctly identify if a given date is “tomorrow” considering both time and date.