UNPKG

@burglekitt/gmt

Version:

Temporal-based date and time utilities with timezone support and polyfill integration

42 lines (41 loc) 1.39 kB
import { Temporal } from "@js-temporal/polyfill"; import { normalizeDateTime } from "../../internal/normalizeDateTime.js"; import { normalizeTimeZone } from "../../internal/normalizeTimeZone.js"; import { isValidUnixUnit } from "../validate/index.js"; function parseEpochMs(value, epochUnit) { let n; if (typeof value === "number") { n = value; } else if (typeof value === "string") { const trimmed = value.trim(); if (!/^-?\d+$/.test(trimmed)) return null; n = Number(trimmed); } else { return null; } if (!Number.isFinite(n)) return null; return epochUnit === "seconds" ? n * 1000 : n; } export function formatUnix(value, locale, options) { const { epochUnit = "milliseconds", timeZone, includeTimeZoneName = false, ...intlOptions } = options ?? {}; if (!isValidUnixUnit(epochUnit)) return ""; const ms = parseEpochMs(value, epochUnit); if (ms === null) return ""; const tz = normalizeTimeZone(timeZone); try { const zdt = Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO(tz); const out = includeTimeZoneName ? zdt.toLocaleString(locale, intlOptions) : zdt.toPlainDateTime().toLocaleString(locale, intlOptions); return normalizeDateTime(out); } catch { return ""; } }