Subtract Years from a Date in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Photo from Unsplash

Subtract Years from a Date in JavaScript #

To subtract years from a date:

  1. Use the getFullYear() method to get the year of the specific date.
  2. Use the setFullYear() method to set the year for the date.
  3. The setFullYear method takes a number representing the year as a parameter and sets the value for the date.
index.js
function subtractYears(numOfYears, date = new Date()) { date.setFullYear(date.getFullYear() - numOfYears); return date; } // 👇️ subtract 1 year from current Date const result = subtractYears(1); // 👇️ Subtract 2 years from another Date const date = new Date('2022-04-26'); // 👇️ Sun Apr 26 2020 console.log(subtractYears(2, date));

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

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

We used the getFullYear method to get the year of the given date.

The setFullYear method takes an integer that represents the year as a parameter and sets the value on the date.

Note that the setFullYear 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 subtractYears(numOfYears, date = new Date()) { const dateCopy = new Date(date.getTime()); dateCopy.setFullYear(dateCopy.getFullYear() - numOfYears); return dateCopy; } const date = new Date('2022-04-27'); const result = subtractYears(3, date); console.log(result); // 👉️ Sat Apr 27 2019 console.log(date); // 👉️ Wed Apr 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 setFullYear 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.