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.

45 lines (43 loc) • 2.32 kB
import { zonedDateTimeFrom } from "../../internal/zonedWallClock.js"; import { isValidZonedDateTime } from "../validate/isValidZonedDateTime.js"; // src/zoned/parse/getZonedOffsetAs.ts const NANOSECONDS_PER_MINUTE = 6e10; function isValidZonedOffsetUnit(unit) { return unit === "minutes" || unit === "nanoseconds" || unit === "minute" || unit === "nanosecond"; } /** * Read a zoned value's UTC offset as a number, in the given unit. * * - Subsumes what would otherwise be `getZonedOffsetMinutes` / * `getZonedOffsetNanoseconds` — one differently-scaled reading of the same * underlying quantity through a single parameterized call, following J8's * `getDurationUnit(value, unit)` precedent (Decision 5). * - "nanoseconds" reads Temporal's `offsetNanoseconds` directly. * - "minutes" divides by 60e9 — every IANA offset is a whole number of * minutes, so this never truncates a fraction. * - Negative offsets (west of UTC) return a negative number. * - `unit` accepts the plural or singular name (`"minutes"` or `"minute"`), as Temporal does. * - Returns null on invalid `value` or `unit`. * * @param value zoned ISO 8601 datetime string * @param unit "minutes" | "nanoseconds" (or the singular "minute" | "nanosecond") * @returns the offset in the requested unit, or null on invalid input * * @example getZonedOffsetAs("2024-07-15T12:00:00-03:00[America/Sao_Paulo]", "minutes") // -180 * @example getZonedOffsetAs("2024-05-15T12:00:00+05:45[Asia/Kathmandu]", "minutes") // 345 * @example getZonedOffsetAs("2024-02-29T12:00:00+00:00[UTC]", "nanoseconds") // 0 * @example getZonedOffsetAs("2024-07-15T12:00:00-03:00[America/Sao_Paulo]", "nanoseconds") // -10800000000000 * @example getZonedOffsetAs("2024-07-15T12:00:00-03:00[America/Sao_Paulo]", "minute") // -180 (singular unit name) * @example getZonedOffsetAs("invalid", "minutes") // null * @example getZonedOffsetAs("2024-02-29T12:00:00+00:00[UTC]", "fortnights" as never) // null */ function getZonedOffsetAs(value, unit) { if (!isValidZonedDateTime(value) || !isValidZonedOffsetUnit(unit)) return null; try { const { offsetNanoseconds } = zonedDateTimeFrom(value); return unit === "nanoseconds" || unit === "nanosecond" ? offsetNanoseconds : offsetNanoseconds / NANOSECONDS_PER_MINUTE; } catch { return null; } } export { getZonedOffsetAs };