Skip to content

diffUtcAsDuration

diffUtcAsDuration(value1: string, value2: string, unit: DateTimeDurationUnit, options?: any): string
import { diffUtcAsDuration } from "@northguild/gmt/utc/calculate";

Return the difference between two UTC datetimes as an ISO 8601 duration string,

  • bridging to the duration namespace (see parseDuration, normalizeDuration).
  • Uses Temporal.Instant.until() with largestUnit set to unit, then .toString().
  • Unlike diffUtc, unit is a single unit (not an array) — an ISO duration string already expresses a full multi-unit breakdown via largestUnit alone, so there’s no array-of-units overload here.
  • Returns "" for invalid input (negative diffs are valid and render with a leading -). smallestUnit, roundingIncrement, and roundingMode control optional rounding of the underlying difference before it’s rendered, per Temporal’s DifferenceOptions — same as diffUtc. toStringSmallestUnit, fractionalSecondDigits, and toStringRoundingMode control the precision of the rendered string itself, per Temporal’s ToStringPrecisionOptions (mirroring parseDuration’s options) — kept separate from the .until() rounding options above because both option sets have colliding smallestUnit/roundingMode keys with different Temporal types.
Parameter Type Description
value1 string UTC ISO datetime string (start)
value2 string UTC ISO datetime string (end)
unit DateTimeDurationUnit DateTimeDurationUnit to use as the duration’s largestUnit
options any optional: smallestUnit, roundingIncrement, roundingMode (.until() rounding); toStringSmallestUnit, fractionalSecondDigits, toStringRoundingMode (.toString() precision)

ISO 8601 duration string, or “” on invalid input

diffUtcAsDuration("2024-03-10T12:00:00Z", "2024-03-11T12:00:00Z", "hours") // "PT24H"
diffUtcAsDuration("2024-03-11T12:00:00Z", "2024-03-10T12:00:00Z", "hours") // "-PT24H"
diffUtcAsDuration("invalid", "2024-03-11T12:00:00Z", "hours") // ""

utc/calculate/diffUtcAsDuration.ts