1. Date setFullYear() and getFullYear() Methods
To add years to a Date
in JavaScript, call the getFullYear()
method on the Date
to get the year, then call the setFullYear()
method on the Date
, passing the sum of getFullYear()
and the number of years to add as an argument, i.e., date.setFullYear(date.getFullYear() + years)
.
For example:
function addYears(date, years) {
date.setFullYear(date.getFullYear() + years);
return date;
}
// May 15, 2022
const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addYears(date, 3);
// May 20, 2025
console.log(newDate); // 2025-05-20T00:00:00.000Z
Our addYears()
function takes a Date
object and the number of years to add as arguments, and returns the same object with the newly added years.
The Date getFullYear() method returns a number that represents the year of a particular date.
The Date setFullYear() method sets the year of a date to a specified number.
Avoiding Side Effects
The setFullYear()
method mutates the Date
object it is called on. This introduces a side effect into our addYears()
function. To avoid modifying the passed Date
and create a pure function, make a copy of the Date
and call setFullYear()
on this copy, instead of the original.
function addYears(date, years) {
const dateCopy = new Date(date);
dateCopy.setFullYear(dateCopy.getFullYear() + years);
return dateCopy;
}
// May 15, 2022
const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addYears(date, 3);
// May 20, 2025
console.log(newDate); // 2025-05-20T00:00:00.000Z
// Original not modified
console.log(date); // 2022-05-15T00:00:00.000Z
Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about. This makes it a good practice to limit the number of side effects in your programs.
2. date-fns addYears() Function
Alternatively, we can use the pure addYears()
function from the date-fns
NPM package to quickly add years to a Date
.
import { addYears } from 'date-fns';
// May 15, 2022
const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addYears(date, 3);
// May 20, 2025
console.log(newDate); // 2025-05-20T00:00:00.000Z
// Original not modified
console.log(date); // 2022-05-15T00:00:00.000Z
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.