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';
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)
  • EpochMilliseconds — any object with a epochMilliseconds property (e.g. Temporal.Instant, Temporal.ZonedDateTime)

// TODO: When the Temporal API reaches Stage 4 and is available without // flags in all major runtimes, consider narrowing the union to the // concrete Temporal types for stricter type-checking.

type DateLike = Date | number | string | EpochMilliseconds

An object that exposes an epoch timestamp in milliseconds.

This structural type is satisfied by Temporal.Instant and Temporal.ZonedDateTime (and any future object that carries the same property), so callers can pass Temporal values without importing them.

interface EpochMilliseconds {
  epochMilliseconds: number;
}

View source on GitHub