Add Years to a Date in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

Add Year(s) to a Date in JavaScript #

To add years to 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.
const date = new Date(); console.log(date); // 👉️ Fri Jan 21 2022 // ✅ Add 1 year to a Date (with Mutation) date.setFullYear(date.getFullYear() + 1); console.log(date); // 👉️ Sat Jan 21 2023

We created a Date object using the Date() constructor.

The example uses the current date, but you can pass a date as a parameter to the constructor.

We used the getFullYear method to get the year of the date and added 1 to the result.

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

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.
const date = new Date(); console.log(date); // 👉️ Fri Jan 21 2022 // ✅ Add years to date (Without mutation) const dateCopy = new Date(date.getTime()); dateCopy.setFullYear(date.getFullYear() + 1); console.log(dateCopy); // 👉️ Sat Jan 21 2023 console.log(date); // 👉️ Fri Jan 21 2022

The getTime method returns the number of milliseconds elapsed between the 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.

You might see the setFullYear method get called with 3 parameters. The parameters the method takes are:

  1. year - An integer representing the year, for example 2022.
  2. month (optional) - an integer between 0 and 11 that represents the months January through December.
  3. date (optional) - an integer between 1 and 31 representing the day of the month.
Note that the value for the month is zero-based, where January is 0, February is 1, March is 2, etc.

The month and date parameters are optional, and when not specified, the values returned from the getMonth() and getDate() methods are used.

In other words, when not provided, the month and date remain the same.

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.