The setFullYear()
and getFullYear()
methods of the Date
object can be used to increment or decrement years from a date in JavaScript.
The following example demonstrates how you can add one year to the current date:
const today = new Date()
const nextYear = new Date()
// Add 1 Year
nextYear.setFullYear(today.getFullYear() + 1)
You can also update the existing JavaScript Date
object as shown below:
const date = new Date()
date.setFullYear(date.getFullYear() + 1)
To subtract years from a date in JavaScript, simply minus the number of years when updating the date with the setFullYear()
method:
const today = new Date()
const lastYear = new Date()
// Minus 1 Year
lastYear.setFullYear(today.getFullYear() - 1)
Finally, if you are frequently manipulating dates in JavaScript, add a function to Date
’s prototype and call it directly whenever you want to add or subtract years:
Date.prototype.addYears = function (years) {
const date = new Date(this.valueOf())
date.setFullYear(date.getFullYear() + years)
return date
}
// Add 1 Year
const nextYear = new Date(2022, 10, 15)
console.log(nextYear.addYears(1))
// Wed Nov 15 2023 00:00:00 GMT+0500 (Pakistan Standard Time)
// Minus 1 Year
const lastYear = new Date(2022, 10, 15)
console.log(lastYear.addYears(-1))
// Mon Nov 15 2021 00:00:00 GMT+0500 (Pakistan Standard Time)