Skip to content

Function: toDuration()

toDuration(value, options?): number | undefined

Coerce a loose duration to MILLISECONDS, or undefined when it can’t be interpreted.

Deliberately lenient, because these values are typed by hand into env vars, CLI flags, and config files: whitespace between amount and unit is optional and unlimited, units are case-insensitive, plurals and the common abbreviations are equivalent (2ms === 2 milliseconds, 1h === 1 hr === 1 Hour), and and thousands separators are ignored (1,500 ms, 1 hour and 30 minutes), and terms compose (1h30m). A plain number passes through as milliseconds.

Signs are supported so a duration can express an OFFSET rather than only a length: a leading - (or a trailing ago) makes the result negative, and an unsigned term inherits the previous term’s sign, so -1h30m is -90 minutes rather than -60 + 30. toDate uses that to turn -7d / 7 days ago into an instant relative to now.

An UNKNOWN unit fails the whole parse rather than being skipped - 1 fortnight returning 1 silently would be worse than returning nothing - which is also what keeps toDate from mistaking 1 Jan 2026 for a duration.

A value that is not a duration at all is offered to toDate and, when it IS a date, read as the signed offset from now (date - now), which makes the two functions inverses: a past instant is negative, a future one positive. options.parseDate: false turns that off when only a length of time makes sense - see ToDurationOptions.

unknown

ToDurationOptions = {}

number | undefined

toDuration("30s"); // 30_000
toDuration("1 hour 30 minutes"); // 5_400_000
toDuration("-7 days"); // -604_800_000
toDuration("2 weeks ago"); // -1_209_600_000
toDuration("2026-08-02"); // ms from now to that instant
toDuration("2026-08-02", { parseDate: false }); // undefined
toDuration("soon"); // undefined