Nepali DateNepali DateBikram Sambat Date Engine
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

ParameterTypeRequiredDescription
dateNepaliDateYesThe target NepaliDate instance to compare against.
unit"year" | "month" | "day"YesThe 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")); // -15

Difference 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")); // 14

Difference 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")); // 4

Advertisement

On this page