Skip to content

Function: toDate()

toDate(value, options?): Date | undefined

Coerce a loose date-ish value to a real Date, or undefined when it can’t be interpreted. Accepts, in this order:

  • a Date (passed through; an invalid one is a miss);
  • an epoch NUMBER or numeric string, in seconds or milliseconds (see SECONDS_CEILING);
  • now (and its today spelling), for the current instant;
  • a toDuration expression, resolved RELATIVE TO NOW, so -7d, 7 days ago, and in 30 minutes are all valid instants;
  • anything Date.parse understands (2026-08-02, an ISO/UTC instant).

The epoch unit inference is the reason this exists rather than new Date(value): a bare epoch arrives as a STRING from an env var or a CLI flag as often as it arrives as a number (date +%s, a JSON field, a copied log line), and Date.parse("1785697899") reads that as a YEAR, silently landing 1.7 billion years out. Numeric strings are therefore routed to the epoch path, never to Date.parse.

The duration fallback runs LAST, after Date.parse, so a real date is never mistaken for an offset. options.parseDuration: false removes it entirely when the value must be an absolute instant - see ToDateOptions.

Like toBoolean this NEVER throws and returns undefined for anything uninterpretable, so a caller decides whether a bad value is fatal, a warning, or a fallback.

unknown

ToDateOptions = {}

Date | undefined

toDate("now"); // this instant
toDate("2026-08-02"); // 2026-08-02T00:00:00.000Z
toDate("1785697899"); // seconds -> 2026-08-02T...
toDate(1785697899000); // millis -> the same instant
toDate("30 days ago"); // now - 30d
toDate("30 days ago", { parseDuration: false }); // undefined
toDate("nope"); // undefined