EN
TypeScript - add years to date
3 points
In this article, we would like to show you how to add years to date in TypeScript.
In this example, we create a simple function that takes two arguments:
date
to which we want to add some years (asDate
),years
that we want to add to thedate
(asnumber
).
Practical example:
xxxxxxxxxx
1
const addYears = (date: Date, years: number): Date => {
2
const result = new Date(date);
3
result.setFullYear(result.getFullYear() + years);
4
return result;
5
};
6
7
8
// Usage example:
9
10
const date = new Date('2021-08-30T08:00:00.000Z');
11
12
console.log(addYears(date, 1).toISOString()); // 2022-08-30T08:00:00.000Z
Output:
xxxxxxxxxx
1
2022-08-30T08:00:00.000Z