Increment a Date by 7 Days using JavaScript

avatar

Borislav Hadzhiev

Last updated: Aug 29, 2022

banner

Photo from Unsplash

Increment a Date by 7 Days using JavaScript #

To increment a date by 7 days:

  1. Use the getDate() method to get the day of the month of the specific date.
  2. Use the setDate() method to increment the date by 7 days.
  3. The setDate method takes the day of the month as a parameter and sets the value for the date.
index.js
const date = new Date(); date.setDate(date.getDate() + 7); // 👇️ Thu Feb 03 2022 (today is Jan 27) console.log(date);

The getDate() method returns an integer between 1 and 31 that represents the day of the month for the date.

The setDate() method takes a number that represents the day of the month as a parameter and sets the value on the Date.

The JavaScript 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 year.

index.js
const date = new Date('2022-02-26'); date.setDate(date.getDate() + 7); // 👇️ Sat Mar 05 2022 console.log(date);

Adding 7 days to a Date object that stores the 26th of February automatically adjusted the month.

Note that the setDate method mutates the Date object it was called on. If you don't want to change the Date in place, create a copy of it before calling the method.
index.js
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.

We used the timestamp to create a copy of the Date object, so we don't mutate it in place when calling the setDate method.

Copying the date is quite useful when you have to use the original Date object in other places in your code.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.