Creates a Duration from a count and unit, a plain-English phrase, an ISO 8601 duration string, a fields object, or milliseconds. Fields stay as written until you call balance(), so 90 minutes stays 90 minutes rather than converting to an hour and a half.
lengths.js
import { duration } from 'native-dates';const phrase = duration('1h 30m');const words = duration('2 weeks and 3 days');const iso = duration('PT1H30M');const count = duration(90, 'minutes');const spilled = duration(1.5, 'days');const fields = duration({ hours: 1, minutes: 30 });const ms = duration(1500);spilled.days; // 1spilled.hours; // 12ms.seconds; // 0ms.milliseconds; // 1500
Parameters
inputDurationInputrequired
Number paired with unit, duration phrase, ISO 8601 string, fields object, Duration, or milliseconds.
unitOrOptionsUnit | { loose?: boolean }
Unit name when input is a numeric count, or loose options with @native-dates/plugins/loose.
Returns
Duration
A Duration keeping the written fields, or null when loose mode cannot read input.
With @native-dates/plugins/loose imported, loose mode returns null instead of throwing when user-entered text cannot be parsed as a length:
Pairs a number or numeric string with a unit, spilling fractions into the next smaller unit.
Human phrase
'1h 30m', '2 weeks and 3 days', '-15m'
Reads space, comma, or and-separated quantities with full unit names or abbreviations.
ISO 8601 string
'PT1H30M', 'P2W3D'
Parses standard ISO 8601 duration strings.
Fields object
{ hours: 1, minutes: 30 }
Reads singular or plural unit keys where all non-zero fields share one sign.
Milliseconds
duration(1500), duration(0)
Treats a bare number or numeric string with no unit as milliseconds.
Duration or Temporal
hours(2), Temporal.Duration
Returns an existing Duration unchanged or wraps a Temporal.Duration.
Fractional units and single signs
Fractional counts spill into smaller exact units, so duration(1.5, 'days') becomes 1 day and 12 hours. Because months have no fixed day count, fractional months throw a RangeError, as do mixed-sign phrases like '1h -30m'.
Unit helpers
Unit helpers build single-unit durations that read naturally inside arithmetic calls and expressions. Each helper accepts a positive or negative number, or a numeric string.