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.

40 lines (38 loc) • 1.66 kB
import { isOptionsArgument } from "../../internal/isObject.js"; import { isDateTimeDurationUnitName } from "../../internal/unitNames.js"; import { readDurationUnits } from "../../internal/readDurationUnits.js"; import { resolveOverflow } from "../../internal/resolveOverflow.js"; import { utcInstantOf } from "../../internal/utcInstant.js"; // src/utc/calculate/subtractUtc.ts /** * Subtract a temporal amount from a UTC datetime string and return a new UTC Instant string. * * - Uses Temporal.Instant.from to parse, subtracts duration, returns new Instant. * - Validates duration units and values. * - Returns "" for invalid input. * * @param value ISO UTC datetime string (e.g. "2024-03-10T12:00:00Z") * @param units Partial<Record<DateTimeDurationUnit, number>> object specifying units to subtract * @param options How an out-of-range result is handled * @returns UTC Instant string after subtraction, or "" on invalid input * * @example subtractUtc("2024-03-15T12:00:00Z", { days: 5 }) // "2024-03-10T12:00:00Z" * @example subtractUtc("2024-03-15T12:00:00Z", { months: 1, years: 1 }) // "2023-02-15T12:00:00Z" * @example subtractUtc("invalid", { days: 5 }) // "" */ function subtractUtc(value, units, options) { try { if (!isOptionsArgument(options)) return ""; const instant = utcInstantOf(value); const amounts = readDurationUnits(units, isDateTimeDurationUnitName); if (instant === null || amounts === null) return ""; try { return instant.toZonedDateTimeISO("UTC").subtract(amounts, { overflow: resolveOverflow(options?.overflow) }).toInstant().toString(); } catch { return ""; } } catch { return ""; } } export { subtractUtc };