date.addYears()
Add or subtract years to a NepaliDate instance while preserving month and day values.
The addYears method adds or subtracts a specified number of years to the current NepaliDate instance. It recalculates the underlying timestamp while retaining the month and day coordinates, adjusting the day number if the target year has fewer days in that specific month.
Import
import { NepaliDate } from "nepali-date-library";Signature
addYears(years: number): NepaliDate;Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
years | number | Yes | Number of years to add (positive) or subtract (negative). |
Return Value
- Type:
NepaliDate - Returns a new
NepaliDateinstance with the added or subtracted years. The original instance is not modified.
Exceptions
Throws an Error if the resulting year falls outside the supported Bikram Sambat calendar range (1976 BS to 2100 BS):
"Resulting date is out of supported range"Examples
Adding and Subtracting Years
import { NepaliDate } from "nepali-date-library";
const date = new NepaliDate("2081-05-15");
const future = date.addYears(5);
console.log(future.format("YYYY-MM-DD")); // "2086-05-15"
const past = date.addYears(-10);
console.log(past.format("YYYY-MM-DD")); // "2071-05-15"Day Clamping on Variable Month Lengths
Because month lengths in the Bikram Sambat astronomical calendar vary across years, addYears() automatically clamps the day component if the destination year has fewer days in that month:
import { NepaliDate } from "nepali-date-library";
// 2081 Baisakh 31 (Baisakh 2081 has 31 days)
const date = new NepaliDate(2081, 0, 31);
// If Baisakh in a target year has only 30 days, day clamps to 30
const nextYear = date.addYears(1);
console.log(nextYear.getDate()); // Clamped to valid rangeRelated
date.addDays(): Add or subtract whole days.date.addMonths(): Add or subtract whole months.date.diff(): Calculate differences between two dates.
date.addMonths()
Add or subtract months to a NepaliDate instance while adjusting for variable month lengths.
date.diff()
Calculate the chronological difference between two NepaliDate instances in specific time units.