Last updated: Aug 29, 2022
Photo from Unsplash
To increment a date by 7 days:
getDate()method to get the day of the month of the specific date.
setDate()method to increment the date by
setDatemethod takes the day of the month as a parameter and sets the value for the date.
const date = new Date(); date.setDate(date.getDate() + 7); // 👇️ Thu Feb 03 2022 (today is Jan 27) console.log(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 incrementing the date by X days pushes it into the next month or
const date = new Date('2022-02-26'); date.setDate(date.getDate() + 7); // 👇️ Sat Mar 05 2022 console.log(date);
7 days to a
Date object that stores the 26th of February
automatically adjusted the month.
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-04-21'); const dateCopy = new Date(date.getTime()); dateCopy.setDate(dateCopy.getDate() + 7); // 👇️ Thu Apr 28 2022 console.log(dateCopy); // 👇️ Thu Apr 21 2022 (didn't change original) console.log(date);
The getTime method returns the number of milliseconds elapsed between the 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.