How to Subtract Years From a Date in JavaScript

1. Date setFullYear() and getFullYear() methods

To subtract years from a Date in JavaScript:

  1. Call the getFullYear() method on the Date to get the year.
  2. Subtract the years.
  3. Pass the result of the subtraction to the setFullYear() method.

For example:

function subtractYears(date, years) {
  date.setFullYear(date.getFullYear() - years);
  return date;
}

// Feb 20, 2022
const date = new Date('2022-02-20T00:00:00.000Z');

const newDate = subtractYears(date, 3);

// Feb 20, 2019
console.log(newDate); // 2019-02-20T00:00:00.000Z

Our subtractYears() function takes a Date object and the number of years to subtract as arguments. It returns the same Date object with the years subtracted.

The Date getFullYear() method returns a number that represents the year of a particular Date.

The Date setFullYear() method sets the year of a Date to a specified number.

Avoid side effects

The setFullYear() method mutates the Date object it is called on. This introduces a side effect into our subtractYears() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setFullYear() on this copy, instead of the original.

function subtractYears(date, years) {
  // πŸ‘‡ make copy with "Date" constructor
  const dateCopy = new Date(date);

  dateCopy.setFullYear(date.getFullYear() - years);

  return dateCopy;
}

const date = new Date('2022-02-20T00:00:00.000Z');

const newDate = subtractYears(date, 3);

// Feb 20, 2019
console.log(newDate); // 2019-02-20T00:00:00.000Z

// πŸ‘‡ Original not modified
console.log(date); // 2022-02-20T00:00:00.000Z

Tip: Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about, as they always give the same output for a particular input. This makes it a good practice to limit the number of side effects in your code.

2. date-fns subYears() function

Alternatively, we can use the subYears() function from the date-fns NPM package to quickly subtract years from a Date. It works like our pure subtractYears() function.

import { subYears } from 'date-fns';

const date = new Date('2022-02-20T00:00:00.000Z');

const newDate = subYears(date, 3);

// Feb 20, 2019
console.log(newDate); // 2019-02-20T00:00:00.000Z

// πŸ‘‡ Original not modified
console.log(date); // 2022-02-20T00:00:00.000Z


11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *