Add Weeks to a Date using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 21, 2022

banner

Photo from Unsplash

Add Weeks to a Date using JavaScript #

To add weeks to a date:

  1. Use the getDate() method to get the day of the month of the specific date.
  2. Use the setDate() method to set the day of the month for the date.
  3. The setDate method takes the day of the month as a parameter and sets the value for the date.
index.js
function addWeeks(numOfWeeks, date = new Date()) { date.setDate(date.getDate() + numOfWeeks * 7); return date; } // Add 2 weeks to current Date console.log(addWeeks(2)); // 👇️ Mon Feb 28 2022 console.log(addWeeks(2, new Date('2022-02-14')));

We created a reusable function that takes the number of weeks and a Date object and adds the weeks to the date.

If no Date object is provided to the function, it uses the current date.

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

To add weeks to the day of the month, we have to add 7 days for each week.

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 adding X weeks to the date increments the month and year.

index.js
const date = new Date('2022-02-01'); console.log(date); // 👉️ Tue Feb 01 2022 date.setDate(date.getDate() + 4 * 7); console.log(date); // 👉️ Tue Mar 01 2022

This is very convenient for us because we don't have to worry about the scenario where adding X weeks pushes us into the next month/year.

Note that the setDate method mutates the Date object it was called on. If you don't want to change the Date in place, you can create a copy of it before calling the method.
index.js
function addWeeks(numOfWeeks, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setDate(dateCopy.getDate() + numOfWeeks * 7); return dateCopy; } const date = new Date('2022-02-13'); const result = addWeeks(2, date); console.log(result); // 👉️ Sun Feb 27 2022 console.log(date); // 👉️ Sun Feb 13 2022 (didn't change original)

The getTime method returns the number of milliseconds elapsed between 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.

In general, mutating function arguments is a bad practice, as passing the same parameter to the same function multiple times returns different results.
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.