Skip to content

difference

Calculates the difference between two dates in the specified unit.

Accepts any DateLike input (Date, timestamp, or date string).

Unlike the removed daysDifference, the default 'days' unit is not rounded — it returns the exact fractional number of days. Wrap the result in Math.round if you need a whole-number day count.

Available since v2.0.0

import { difference } from '@helpers4/date';
// or, from the all-in-one package (same code, one install):
import { difference } from 'helpers4/date';
difference(dateA: DateLike, dateB: DateLike, options: DateDifferenceOptions): number
ParameterTypeDescription
dateADateLikeFirst date
dateBDateLikeSecond date
optionsDateDifferenceOptionsDifference options

number — The difference between the two dates, or NaN if either date is invalid

difference('2025-01-01', '2025-01-10')
// => 9
difference('2025-01-01T00:00:00Z', '2025-01-01T12:00:00Z')
// => 0.5 (fractional — use Math.round(difference(a, b)) for a whole-day count)
difference('2025-01-01T00:00:00Z', '2025-01-01T02:30:00Z', { unit: 'hours' })
// => 2.5
difference('2025-01-10', '2025-01-01', { absolute: false })
// => -9

Options for date difference calculation

interface DateDifferenceOptions {
  absolute?: boolean;
  unit?: DifferenceUnit;
}

A value that can be converted to a Date.

  • Date — used as-is (validated for Invalid Date)
  • number — treated as a timestamp (seconds or milliseconds, auto-detected); 0 is treated as invalid and produces null in ensureDate
  • string — parsed via new Date(string)
  • Temporal.Instant | Temporal.ZonedDateTime — read via their epochMilliseconds property
type DateLike = Date | number | string | Temporal.Instant | Temporal.ZonedDateTime

Unit for date difference calculation

type DifferenceUnit = 'milliseconds' | 'seconds' | 'minutes' | 'hours' | 'days'

View source on GitHub