Skip to content

formatDuration

Playground

call
result 
formatDuration(value: string, locale?: string, options?: FormatDurationOptions): string
import { formatDuration } from "@northguild/gmt/duration/format";

Render an ISO 8601 duration string as a locale-aware, human-readable string.

  • Uses Temporal.Duration.from to parse, then Intl.NumberFormat({ style: “unit” }) to render each nonzero year/month/week/day/hour/minute/second component with correct per-locale unit labels and pluralization, joined via Intl.ListFormat.
  • Sub-second components (milliseconds/microseconds/nanoseconds) are folded into the seconds component as a fractional value (e.g. “PT1.5S” -> one “1.5 seconds” component), since Intl.NumberFormat’s “second” unit accepts fractional input.
  • By default, zero-valued components are omitted (e.g. “P1DT0H30M” -> “1 day, 30 minutes”). Pass { zero: true } to include them.
  • A zero-length duration (e.g. “PT0S”) always renders its seconds component (“0 seconds”) even with the default zero-omitting behavior, since omitting every component would otherwise produce “”.
  • Negative durations render each component with a leading “-” (Temporal stores every field of a negative duration as a negative number).
  • Returns “” for invalid input: non-string value or invalid duration string.
Parameter Type Description
value string ISO 8601 duration string
locale string BCP 47 locale tag, passed to Intl.NumberFormat/Intl.ListFormat; system default if omitted

options

Option Type Default
style? "long" | "short" | "narrow"
zero? boolean

human-readable rendering of the duration, or “” on invalid input

formatDuration("P1DT2H30M", "en-US") // "1 day, 2 hours, and 30 minutes"
formatDuration("PT90M", "en-US", { style: "short" }) // "90 min"
formatDuration("PT90M", "en-US", { style: "narrow" }) // "90m"
formatDuration("P1DT0H30M", "en-US") // "1 day and 30 minutes"
formatDuration("PT0S", "en-US") // "0 seconds"
formatDuration("-P1DT2H", "en-US") // "-1 day and -2 hours"
formatDuration("P1DT2H30M", "de-DE") // "1 Tag, 2 Stunden und 30 Minuten"
formatDuration("invalid") // ""

duration/format/formatDuration.ts