Subtract Months from a Date in JavaScript


Borislav Hadzhiev

Fri Jan 21 20222 min read

Subtract Months from a Date in JavaScript #

To subtract months from a date:

  1. Use the getMonth() method to get a zero-based value for the month of the specific date.
  2. Use the setMonth() method to set the month for the date.
  3. The setMonth method takes a zero-based number for the month and sets the value for the date.
function subtractMonths(numOfMonths, date = new Date()) { date.setMonth(date.getMonth() - numOfMonths); return date; } // 👇️ Subtract 1 Month from current Date const result = subtractMonths(1); // 👇️ Subtract 2 months from another Date const date = new Date('2022-04-27'); // 👇️ Sun Feb 27 2022 console.log(subtractMonths(2, date));

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

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

The getMonth() method returns an integer between 0 (January) and 11 (December), representing the month in the given date.

Notice that the value is zero-based, e.g. January = 0, February = 1, March = 2, etc.

The setMonth() method takes a zero-based value representing the month of the year (0 = January, 1 = February, etc.) and sets the value for the date.

The JavaScript Date object automatically takes care of adjusting the year if subtracting X months from the date pushes us into the previous year.

const date = new Date('2022-01-27'); date.setMonth(date.getMonth() - 2); console.log(date); // 👉️ Sat Nov 27 2021

We subtracted 2 months from a date in January 2022. The result shows that the year automatically got adjusted to 2021.

Note that the setMonth 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.
function subtractMonths(numOfMonths, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setMonth(dateCopy.getMonth() - numOfMonths); return dateCopy; } // 👇️ Subtract 2 months from another Date const date = new Date('2022-03-27'); const result = subtractMonths(2, date); console.log(result); // 👉️ Thu Jan 27 2022 console.log(date); // 👉️ Sun Mar 27 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 setMonth 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.
Use the search field on my Home Page to filter through my more than 1,000 articles.