Methods
date.diff()
Calculate the chronological difference between two NepaliDate instances in specific time units.
The diff method calculates the elapsed time duration between the current NepaliDate instance and another date object. It can return the difference in days, months, years, hours, minutes, seconds, or milliseconds, making it suitable for calculating age, tenure, or interval durations.
Import
import { NepaliDate } from "nepali-date-library";Signature
diff(date: NepaliDate, unit: "year" | "month" | "day"): number;Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
date | NepaliDate | Yes | The target NepaliDate instance to compare against. |
unit | "year" | "month" | "day" | Yes | The unit of measurement for the difference calculation. |
Return Value
- Type:
number - The numeric difference between the two dates (
this - date). - Positive if the current date is after
date. - Negative if the current date is before
date. - Zero if they are identical in the evaluated unit.
Calculation Rules
"day": Computed using Unix timestamps:Math.floor((this.getTime() - date.getTime()) / 86400000)."month": Computed using calendar month indices:(this.year - date.year) * 12 + (this.month - date.month)."year": Computed by year difference:this.year - date.year.
Exceptions
Throws an Error if an invalid unit string is supplied:
"Invalid unit for diff calculation"Examples
Difference in Days
import { NepaliDate } from "nepali-date-library";
const date1 = new NepaliDate("2081-01-20");
const date2 = new NepaliDate("2081-01-05");
console.log(date1.diff(date2, "day")); // 15
console.log(date2.diff(date1, "day")); // -15Difference in Months
import { NepaliDate } from "nepali-date-library";
const date1 = new NepaliDate("2081-06-15");
const date2 = new NepaliDate("2080-04-15");
console.log(date1.diff(date2, "month")); // 14Difference in Years
import { NepaliDate } from "nepali-date-library";
const date1 = new NepaliDate("2085-01-01");
const date2 = new NepaliDate("2081-01-01");
console.log(date1.diff(date2, "year")); // 4Related
date.isBefore(): Check if a date precedes another.date.isAfter(): Check if a date succeeds another.date.isEqual(): Check if two dates are equal.
Advertisement
date.addYears()
Add or subtract years to a NepaliDate instance while preserving month and day values.
date.startOfDay()
Return a new NepaliDate instance set to the first moment of the current day at midnight.