@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.
50 lines (48 loc) • 1.84 kB
JavaScript
import { Temporal } from "../temporal.js";
// src/internal/temporalCompat/islamicEra.ts
const formatters = /* @__PURE__ */ new Map();
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;
function formatterFor(calendarId) {
let format = formatters.get(calendarId);
if (format === void 0) {
format = new Intl.DateTimeFormat(`en-u-ca-${calendarId}`, {
era: "short",
year: "numeric",
month: "numeric",
day: "numeric",
timeZone: "UTC"
});
formatters.set(calendarId, format);
}
return format;
}
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 };