Fri Jan 21 2022·2 min read
Photo by Chad Madden
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 as a parameter 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, you can create a copy of it 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 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 = 0, February = 1, March = 2, etc.
date parameters are optional, and when not specified, the
values returned from the
getDate() methods are used, in other
words the month and date remain the same.