Skip to content

closestDateTo

closestDateTo(target: string, candidates: string[]): string
import { closestDateTo } from "@northguild/gmt/plain/calculate";

Return the candidate date nearest to target by calendar distance.

  • Distance is measured in whole days using Temporal.PlainDate.compare.
  • Returns null if the candidates array is empty or contains no valid dates.
  • Returns null if target is invalid.
  • On a tie (two equidistant candidates), returns the first one in array order.
Parameter Type Description
target string ISO PlainDate string to measure distance from
candidates string[] Array of ISO PlainDate strings to choose from

The nearest candidate date string, or null on invalid input

closestDateTo("2024-03-15", ["2024-03-01", "2024-03-20", "2024-03-18"]) // "2024-03-18"
closestDateTo("2024-03-15", ["2024-03-01", "2024-03-29"]) // "2024-03-01"
closestDateTo("2024-03-15", []) // null
closestDateTo("invalid", ["2024-03-01"]) // null

plain/calculate/closestDateTo.ts