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 itstodayspelling), for the current instant;- a toDuration expression, resolved RELATIVE TO NOW, so
-7d,7 days ago, andin 30 minutesare all valid instants; - anything
Date.parseunderstands (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.
Parameters
Section titled “Parameters”unknown
options?
Section titled “options?”ToDateOptions = {}
Returns
Section titled “Returns”Date | undefined
Example
Section titled “Example”toDate("now"); // this instanttoDate("2026-08-02"); // 2026-08-02T00:00:00.000ZtoDate("1785697899"); // seconds -> 2026-08-02T...toDate(1785697899000); // millis -> the same instanttoDate("30 days ago"); // now - 30dtoDate("30 days ago", { parseDuration: false }); // undefinedtoDate("nope"); // undefined