Last updated: Jul 25, 2022
Photo from Unsplash
To add years to a date:
getFullYear()method to get the year of the specific date.
setFullYear()method to set the year for the date.
setFullYearmethod 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
The example uses the current date, but you can pass a date as a parameter to the constructor.
We used the
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.
setFullYearmethod mutates the
Dateobject it was called on. If you don't want to change the
Datein 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.
Dateobject, so we don't mutate it in place when calling the
You might see the
setFullYear method get called with 3 parameters. The
parameters the method takes are:
year- An integer representing the year, for example
month(optional) - an integer between
11that represents the months January through December.
date(optional) - an integer between
31representing the day of the month.
monthis zero-based, where January is 0, February is 1, March is 2, etc.
date parameters are optional, and when not specified, the
values returned from the
getDate() methods are used.
In other words, when not provided, the month and date remain the same.