Last updated: Jul 25, 2022
Photo from Unsplash
To add 1 day to a date:
getDate()method to get the day of the month for the given date.
setDate()method to set the day of the month to the next day.
setDatemethod will add 1 day to the
const date = new Date(); date.setDate(date.getDate() + 1); // ✅ 1 Day added console.log(date);
We used the
constructor to create a
Date object that represents the current date.
method returns an integer between
31 that represents the day of the
month for the date.
method takes a number that represents the day of the month as a parameter and
sets the value on the
Date object automatically takes care of rolling over the month
and/or year if adding a day to the date increments the month and year.
const date = new Date('2022-02-28'); date.setDate(date.getDate() + 1); // ✅ Tue Mar 01 2022 console.log(date);
The example shows how creating a date for the 28th of February 2022 and adding
1 day to the result rolls the month over to March.
setDatemethod mutates the
Dateobject it was called on. If you don't want to change the
Datein place, create a copy of it before calling the method.
const date = new Date('2022-02-21'); const dateCopy = new Date(date.getTime()); dateCopy.setDate(dateCopy.getDate() + 1); // 👇️ Tue Feb 22 2022 console.log(dateCopy); // 👇️ Mon Feb 21 2022 (didn't change original) console.log(date);
The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.
Dateobject, so we don't mutate it in place when calling the
Copying the date is quite useful when you have to use the original
in other places in your code.