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.

57 lines (55 loc) • 2.21 kB
import { Temporal } from "../temporal.js"; import { guardedDateTimeFormat } from "../formatterCache.js"; // src/internal/temporalCompat/islamicEra.ts const modernEras = /* @__PURE__ */ new Map(); /** A date after the epoch of every calendar GMT supports: the era every modern date prints in. */ const MODERN_DATE_MS = Temporal.PlainDate.from("2000-01-01").toZonedDateTime("UTC").epochMilliseconds; /** * The formatter whose parts the polyfill reads. Built with the week-year guard (CORE-112: * `formatToParts` is never called on a formatter that could abort) and without the year repairs, * which answer `[]` for a date before the Hijra (D26): the era printed there is what this file * reads. */ const formatters = /* @__PURE__ */ new Map(); function formatterFor(calendarId) { let formatter = formatters.get(calendarId); if (formatter === void 0) { formatter = guardedDateTimeFormat(`en-u-ca-${calendarId}`, { era: "short", year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" }); formatters.set(calendarId, formatter); } return formatter; } function eraPartAt(calendarId, ms) { return formatterFor(calendarId).formatToParts(ms).find((part) => part.type === "era")?.value; } function modernEraOf(calendarId) { if (!modernEras.has(calendarId)) modernEras.set(calendarId, eraPartAt(calendarId, MODERN_DATE_MS)); return modernEras.get(calendarId); } /** * Midnight UTC of `date` as an epoch millisecond count, what `Intl.DateTimeFormat` formats. * `-271821-04-19`, the one PlainDate whose midnight precedes the first instant, is read as the * next day: both lie in the same era of every calendar. */ function timeValueOf(date) { const iso = date.withCalendar("iso8601"); try { return iso.toZonedDateTime("UTC").epochMilliseconds; } catch { return iso.add({ days: 1 }).toZonedDateTime("UTC").epochMilliseconds; } } /** * True when the runtime prints `date` in the same era as a modern date of `calendarId`. False * only on a runtime that prints a second era for dates before the calendar's epoch (D18). */ function printsInModernEra(date, calendarId) { return eraPartAt(calendarId, timeValueOf(date)) === modernEraOf(calendarId); } export { printsInModernEra };