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.

58 lines (56 loc) • 2.14 kB
import { frameNowWallClock, zoneFrame } from "../../internal/zoneFrame.js"; import { resolveDateTimeUnit } from "../../internal/resolveDateTimeUnit.js"; import { weekNumberOf } from "../../internal/weekNumber.js"; import { zonedNowUnitValue } from "../../internal/zonedNowUnitValue.js"; // src/zoned/get/getZonedNowUnit.ts function isValidZonedNowUnit(unit) { return [ "year", "month", "week", "day", "dayOfWeek", "hour", "minute", "second", "millisecond", "microsecond", "nanosecond" ].includes(unit); } /** * Return the requested current unit value for the specified IANA timeZone. * * - Uses nowZonedDateTimeISO() to get the current time. * - `week` is the ISO 8601 week number, from `parseWeekFromDate`. * - Validation is performed on timezone and unit. * - `unit` accepts the singular or plural name of a Temporal unit (`"hour"` or `"hours"`), as Temporal * does; `"dayOfWeek"` has no plural. * - The `"year"` unit is written as Temporal writes a year: four digits (`"2024"`, `"0005"`), or a * sign and six digits outside 0000–9999 (`"+010000"`, `"-000005"`). * * @param ianaTimezone IANA name or UTC offset: a time zone identifier (`+05:30`, `+0530`, `-08`) or * a stored offset (`±HH:MM[:SS]`, what `getTimeZoneOffset` returns) * @param unit unit to extract from current zoned time * @returns string representation of the requested unit or "" on invalid input * * @example getZonedNowUnit("Asia/Tokyo", "hour") // "23" * @example getZonedNowUnit("UTC", "hours") // "14", if the UTC time is 14:xx (plural unit name) * @example getZonedNowUnit("invalid", "hour") // "" */ function getZonedNowUnit(ianaTimezone, unit) { if (typeof unit !== "string") return ""; const resolvedUnit = resolveDateTimeUnit(unit); const frame = zoneFrame(ianaTimezone); if (frame === null || !isValidZonedNowUnit(resolvedUnit)) return ""; try { const now = frameNowWallClock(frame); return zonedNowUnitValue(now, resolvedUnit, (wallClock) => { const w = weekNumberOf(wallClock.toPlainDate(), "monday"); return w === null ? "" : w.toString(); }); } catch { return ""; } } export { getZonedNowUnit };