Borislav Hadzhiev
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.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 as a parameter and sets the value on the date.
setFullYear
method mutates the Date
object it was called on. If you don't want to change the Date
in 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.
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:
year
- An integer representing the year, for example 2022
.month
(optional) - an integer between 0
and 11
that represents the
months January through December.date
(optional) - an integer between 1
and 31
representing the day of
the month.month
is zero-based, where January = 0, February = 1, March = 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 the month and date remain the same.