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.

34 lines (32 loc) • 1.66 kB
import { isZoneId } from "./inputChecks.js"; import { systemTimeZone } from "./resolveLocale.js"; // src/internal/normalizeTimeZone.ts /** * Resolve the `timeZone` option of the `unix/` and `utc/` functions that hand the zone to * `Intl.DateTimeFormat`, which takes a time zone identifier only. A function whose result names no * zone reads its option with `normalizeZoneFrame` instead, which also accepts a stored UTC offset * with seconds. * * - Omitted (`undefined`) → `"UTC"`. A Unix epoch and a UTC string name an instant, so no host * zone is read unless asked for. * - `"local"` → the system time zone (`systemTimeZone()`), or `""` when the host reports none * that is valid. * - A valid IANA identifier or UTC offset (`"+05:30"`) → returned as-is. * - Anything else (`null`, `""`, a typo, a non-string) → `""`, the caller's cue to return its * sentinel. ECMA-402 `Intl.DateTimeFormat` and Temporal `ToTemporalTimeZoneIdentifier` throw * `RangeError` for an unknown zone, so a typo never silently renders UTC. * * @param timeZone the caller's `timeZone` option * @returns the zone to use, or `""` when invalid * * @example normalizeTimeZone(undefined) // "UTC" * @example normalizeTimeZone("local") // system zone, e.g. "Asia/Tokyo" * @example normalizeTimeZone("Europe/Helsinki") // "Europe/Helsinki" * @example normalizeTimeZone("America/New_Yrok") // "" */ function normalizeTimeZone(timeZone) { if (timeZone === void 0) return "UTC"; const resolved = timeZone === "local" ? systemTimeZone() : timeZone; return typeof resolved === "string" && resolved.length > 0 && isZoneId(resolved) ? resolved : ""; } export { normalizeTimeZone };