Subtract Weeks from a Date in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 21, 2022

banner

Check out my new book

Subtract Weeks from a Date in JavaScript #

To subtract weeks from a date:

  1. Use the getDate() method to get the day of the month for 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 parameter and sets the value for the date.
index.js
function subtractWeeks(numOfWeeks, date = new Date()) { date.setDate(date.getDate() - numOfWeeks * 7); return date; } // 👇️ Subtract 1 week from current date const result = subtractWeeks(1); console.log(result); // 👇️ Subtract 2 weeks from another date // 👇️ Thu Feb 03 2022 console.log(subtractWeeks(2, new Date('2022-02-17')));

We created a reusable function that takes the number of weeks and a Date object and subtracts the weeks from 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 subtract weeks from the day of the month, we have to subtract 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 adjusting the month and year, if subtracting X weeks from the date pushes us into the previous month or year.

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

Subtracting 4 weeks from the date automatically adjusted the month in the example.

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 subtractWeeks(numOfWeeks, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setDate(dateCopy.getDate() - numOfWeeks * 7); return dateCopy; } const date = new Date('2022-04-27'); const result = subtractWeeks(3, date); console.log(result); // 👉️ Wed Apr 06 2022 console.log(date); // 👉️ Wed Apr 27 2022

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.