Skip to content

compare

Comparison of two dates.

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

Available since v2.0.0

import { compare } from '@helpers4/date';
// or, from the all-in-one package (same code, one install):
import { compare } from 'helpers4/date';
compare(dateA: DateLike, dateB: DateLike, options: DateCompareOptions): boolean
ParameterTypeDescription
dateADateLikeFirst date to compare
dateBDateLikeSecond date to compare
optionsDateCompareOptionsComparison options

boolean — true if dates are identical according to the specified precision, false otherwise

By default, two identical Date objects are equal.

const d = new Date('2025-01-19T12:00:00Z');
compare(d, new Date('2025-01-19T12:00:00Z'))
// => true

Using day precision ignores the time part.

compare(
  new Date('2025-01-19T08:00:00Z'),
  new Date('2025-01-19T23:59:59Z'),
  { precision: 'days' }
)
// => true

Options for date comparison

interface DateCompareOptions {
  precision?: "milliseconds" | "seconds" | "minutes" | "hours" | "days" | "months" | "years";
}

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

View source on GitHub