To get tomorrow’s date in JavaScript, we can use the built-in Date()
method with the getDate()
and the setDate()
methods.
The Date()
can be used as a function as well as a constructor i.e. new Date()
. When we use the Date()
function as a constructor i.e. with the new
keyword, it returns a date object based on the parameters passed to it.
If no parameters are passed to the Date()
constructor, it returns the current date-time object. So, if we want to get tomorrow’s date, we can simply add +1 to this current date-time object.
// Get today's date const today = new Date(); console.log(today); // Output: Sun Nov 20 2022 20:46:08 ... let tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1); console.log(tomorrow); // Output: Mon Nov 21 2022 20:46:08 ...
If we are at the end of the month and add +1 to the current date, we will automatically get the first day of the next month i.e. tomorrow’s date. Therefore, we don’t have to explicitly handle such situations as JavaScript implicitly does this job for us.
// Set date to 31st January const date = new Date('2022-01-31'); // Add +1 to above date date.setDate(date.getDate() + 1); console.log(date); // Output: Tue Feb 01 2022 05:30:00 ...
Notice that we have used two built-in methods getDate()
and setDate()
.
The getDate()
method returns an integer between 1 and 31 representing the day of the month for the specified date.
const today = new Date(); console.log(today.getDate()); // Output: 20 const date = new Date('2021-05-15'); console.log(date.getDate()); // Output: 15
The setDate()
method sets the day of the month for a given date. The day value is passed as a parameter to the setDate()
method.
Something like this:
const date = new Date('2021-06-14'); // Set day of month to 10 date.setDate(10); console.log(date); // Output: Thu Jun 10 2021 05:30:00 ...
Get Yesterday’s Date using Date() Method
To get yesterday’s date, we can simply subtract 1 from today’s date and then set the new date using the built-in setDate()
method.
Something like this:
// Get today's date const today = new Date(); console.log(today); // Output: Sun Nov 20 2022 21:35:50 ... let yesterday = new Date(); yesterday.setDate(today.getDate() - 1); console.log(yesterday); // Output: Sat Nov 19 2022 21:35:50 ...
Conclusion
In this article, we learned how we can get tomorrow’s date in JavaScript.
To get tomorrow’s date, we first get today’s date using the Date()
constructor and then simply add +1 to today’s date using the setDate()
and getDate()
methods to get tomorrow’s date.