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.

44 lines (42 loc) • 1.97 kB
import { nowZonedDateTimeISO } from "../../internal/temporalCompat/clock.js"; import { isValidTimeZone } from "../validate/isValidTimeZone.js"; import { isOptionsArgument } from "../../internal/isObject.js"; import { optionOrDefault } from "../../internal/optionOrDefault.js"; // src/zoned/get/getZonedNow.ts /** * Return the current zoned datetime for the specified IANA timeZone. * * - Uses nowZonedDateTimeISO() to get the current time. * - Validation is performed on the timezone. * - `smallestUnit` is the only option read. Any other key on `optionsArg` is ignored, so the * string always carries the offset and the bracketed time zone, and smaller units are always * truncated. * - An offset with seconds (`-00:44:30`) returns `""`. A written zone cannot carry seconds (RFC * 9557 §4.1), so the result could not name it. Pass the IANA name, or call * `fromOffsetInstant({ instant, offset })` for the local time with its full offset and no * bracket. * * @param ianaTimezone IANA name or a UTC offset to the minute (what `isValidTimeZone` accepts) * @param optionsArg optional setting for the precision of the output string * @returns zoned ISO 8601 datetime string or "" on invalid input * * @example getZonedNow("Asia/Tokyo") // "2024-02-29T23:30:45.123+09:00[Asia/Tokyo]" * @example getZonedNow("Asia/Tokyo", { smallestUnit: "second" }) // "2024-02-29T23:30:45+09:00[Asia/Tokyo]" * @example getZonedNow("Invalid/Zone") // "" * @example getZonedNow("Asia/Tokyo", { smallestUnit: "fortnight" as never }) // "" (not a unit from minute to nanosecond) */ function getZonedNow(ianaTimezone, optionsArg) { try { if (!isOptionsArgument(optionsArg)) return ""; const options = { smallestUnit: optionOrDefault(optionsArg?.smallestUnit, "millisecond") }; if (!isValidTimeZone(ianaTimezone)) return ""; try { return nowZonedDateTimeISO(ianaTimezone).toString(options); } catch { return ""; } } catch { return ""; } } export { getZonedNow };