Subtract Days from a Date in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Subtract Days from a Date in JavaScript #

To subtract days 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 a parameter and sets the value for the date.
index.js
function subtractDays(numOfDays, date = new Date()) { date.setDate(date.getDate() - numOfDays); return date; } // 👇️ Subtract 1 day from the current date const result = subtractDays(1); // 👇️ Subtract 2 days from another date // 👇️ Tue Mar 22 2022 console.log(subtractDays(2, new Date('2022-03-24')));

We created a reusable function that takes the number of days and a Date object and subtracts the days from the date.

If no Date object is provided, the function uses the current 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.

If a negative number is provided to the setDate method, the date will be set counting backwards from the last day of the previous month.

In other words, the JavaScript Date object automatically takes care of adjusting the month and year, if subtracting X days from the date pushes us into the previous month or year.

index.js
const date = new Date('2022-05-02'); date.setDate(date.getDate() - 5); console.log(date); // 👉️ Wed Apr 27 2022

Subtracting 5 days from the date automatically adjusted the month in the example above.

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 before calling the method.
index.js
function subtractDays(numOfDays, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setDate(dateCopy.getDate() - numOfDays); return dateCopy; } const date = new Date('2022-06-22'); const result = subtractDays(6, date); console.log(result); // 👉️ Thu Jun 16 2022 console.log(date); // 👉️ Wed Jun 22 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 argument to the same function multiple times produces 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.