UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

35 lines (33 loc) • 1.22 kB
import { Temporal } from "../../internal/temporal.js"; import { isOptionsArgument } from "../../internal/isObject.js"; // src/duration/parse/parseDuration.ts /** * Parse and re-normalize an ISO 8601 duration string. * * - Uses Temporal.Duration.from to parse, then .toString() to re-emit. * - Returns "" for invalid input. * * @param value ISO 8601 duration string * @param options The precision of the string written back, as Temporal's ToStringPrecisionOptions * @returns re-normalized ISO 8601 duration string, or "" on invalid input * * @example parseDuration("P1DT2H30M") // "P1DT2H30M" * @example parseDuration("PT1.5S") // "PT1.5S" * @example parseDuration("PT1.5S", { smallestUnit: "second" }) // "PT1S" * @example parseDuration("PT1.5S", { fractionalSecondDigits: 3 }) // "PT1.500S" * @example parseDuration("invalid") // "" */ function parseDuration(value, options) { if (!isOptionsArgument(options)) return ""; if (typeof value !== "string") return ""; try { return Temporal.Duration.from(value).toString({ smallestUnit: options?.smallestUnit, fractionalSecondDigits: options?.fractionalSecondDigits, roundingMode: options?.roundingMode }); } catch { return ""; } } export { parseDuration };