@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.
213 lines (211 loc) • 8.96 kB
JavaScript
import { Temporal } from "./temporal.js";
import { isIslamicEpochEraCompatNeeded } from "./temporalCompat/capabilities.js";
import { markRangeHandled, rangeHooks } from "./rangeHooks.js";
import { digitRuns, digitSetOf, digitsOf } from "./weekYearText.js";
import { showsEraOrYear, toMilliseconds } from "./yearPrinting.js";
// src/internal/islamicEpochEra.ts
/** The days in 210 islamic years (7 cycles of 30 tabular years): 10631 whole weeks. */
const CYCLE_DAYS = 74417;
/** The years in one cycle. */
const CYCLE_YEARS = 210;
/**
* Days in year 0 and in year 1: both are common years of 354 days in the 30-year tabular cycle
* (Calendrical Calculations, chapter 6: the leap years are 2, 5, 7, 10, 13, 16, 18, 21, 24, 26
* and 29), which the umalqura calendar follows before its table.
*/
const YEAR_DAYS = 354;
/** The ISO date of 1 Muharram of year 1 (Calendrical Calculations, chapter 6). */
const EPOCH_DAY = {
"islamic-civil": "0622-07-19",
"islamic-tbla": "0622-07-18",
"islamic-umalqura": "0622-07-19"
};
/**
* The instant JavaScriptCore changes the era at (WebKit bug 331724), per calendar: 07:52:58Z on the
* epoch day. A later date of year 1 before it (a fixed offset east of +16:07:02) is still read as
* year 0.
*/
const ENGINE_ERA_SWITCH_MS = {
"islamic-civil": Temporal.Instant.from("0622-07-19T07:52:58Z").epochMilliseconds,
"islamic-tbla": Temporal.Instant.from("0622-07-18T07:52:58Z").epochMilliseconds,
"islamic-umalqura": Temporal.Instant.from("0622-07-19T07:52:58Z").epochMilliseconds
};
/** The cycle counts tried for a range, so a far end cannot print the year a moved end prints. */
const TRIES = [
1,
3,
5
];
/** The local days of `ms` since 1 Muharram of year 1 in a zone, or `null` when there is none. */
function daysSinceEpoch(ms, timeZone, epoch) {
try {
return Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO(timeZone).toPlainDate().since(epoch, { largestUnit: "days" }).days;
} catch {
return null;
}
}
/** The instant `cycles` cycles later (earlier when negative) at the same wall-clock time. */
function shiftedBy(ms, timeZone, cycles) {
try {
const start = Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO(timeZone);
const moved = start.add({ days: CYCLE_DAYS * cycles });
return moved.toPlainTime().equals(start.toPlainTime()) ? moved.epochMilliseconds : null;
} catch {
return null;
}
}
/** The value of a digit run, in a numbering system's digit table. */
function valueOf(run, table) {
return [...run].reduce((sum, character) => sum * 10 + Math.max(0, table.indexOf(character)), 0);
}
/**
* The range text with each year run that differs between the moved range (`text`) and the range
* one cycle further (`later`) written as year 1, or `null` when those runs are not the years the
* moves predict (a far end printed the same year, or the engine laid the range out differently).
*/
function rewriteYears(text, later, { digitSet, table, one, twoDigitOne }, { cycles, moving, mixed }) {
const runs = digitRuns(text, digitSet);
const twins = digitRuns(later, digitSet);
if (runs.length !== twins.length) return null;
const changed = runs.filter((run, at) => run.text !== twins[at]?.text);
if (changed.length < (mixed ? 2 : 1) || changed.length > moving) return null;
const twoDigit = changed.every((run) => [...run.text].length <= 2);
const printed = 1 + CYCLE_YEARS * cycles;
if (!changed.every((run) => valueOf(run.text, table) === (twoDigit ? printed % 100 : printed))) return null;
let result = text;
for (const run of changed.toReversed()) result = result.slice(0, run.start) + (twoDigit ? twoDigitOne : one) + result.slice(run.end);
return result;
}
/** 1 for a day of year 1, -1 for a day of year 0, 0 for any other day. */
function kindOf(days) {
if (days === null) return 0;
if (days >= 0 && days < YEAR_DAYS) return 1;
return days < 0 && days >= -354 ? -1 : 0;
}
/**
* Whether an instant is one JavaScriptCore can print with the wrong era: its local date is the
* epoch day or the day before, or a later date of year 1 whose instant is before the engine's
* switch.
*/
function isAtRisk(days, ms, calendar) {
return days === 0 || days === -1 || days !== null && days > 0 && ms < (ENGINE_ERA_SWITCH_MS[calendar] ?? Number.NEGATIVE_INFINITY);
}
/**
* The instant a date on the epoch day or the day before is read at instead, with its era side (1
* for the Hijra and after, -1 before it), or `null` when the instant needs no move: the calendar
* is not islamic, the engine has no D32, the local date is not at risk or no same-time twin exists.
*
* @example epochTwin(Date.UTC(622, 6, 19), "islamic-civil", "UTC") // { ms: 74417-day-later instant, side: 1 }
*/
function epochTwin(ms, calendar, timeZone) {
const epochText = EPOCH_DAY[calendar];
if (epochText === void 0 || !isIslamicEpochEraCompatNeeded()) return null;
const days = daysSinceEpoch(ms, timeZone, Temporal.PlainDate.from(epochText));
if (!isAtRisk(days, ms, calendar)) return null;
const side = kindOf(days) === 1 ? 1 : -1;
const moved = shiftedBy(ms, timeZone, side);
return moved === null ? null : {
ms: moved,
side
};
}
/**
* The formatter itself, or a wrapper that prints the first day of year 1 of an islamic calendar as
* year 1 in the era AH, and the last day of year 0 as the formatter prints any other date before
* the Hijra, where the engine changes the era in the middle of the day (D32).
*
* @param formatter the formatter the earlier repairs returned
* @param callerOptions the options it was built with
* @returns the formatter, or its wrapper
*
* @example repairIslamicEpochEra(new Intl.DateTimeFormat("en-u-ca-gregory"), {}) // the same formatter
* @example repairIslamicEpochEra(new Intl.DateTimeFormat("en-u-ca-islamic-civil", { era: "short", year: "numeric", timeZone: "UTC" }), { era: "short", year: "numeric", timeZone: "UTC" }).format(Date.UTC(622, 6, 19)) // "1 AH" where the engine prints "0 Before Hijra"
*/
function repairIslamicEpochEra(formatter, callerOptions) {
let resolved;
try {
resolved = formatter.resolvedOptions();
} catch {
return formatter;
}
const epochText = EPOCH_DAY[resolved.calendar];
if (epochText === void 0 || !showsEraOrYear(callerOptions) || !isIslamicEpochEraCompatNeeded()) return formatter;
const { timeZone, numberingSystem, locale } = resolved;
const epoch = Temporal.PlainDate.from(epochText);
const table = digitsOf(numberingSystem);
const digitSet = digitSetOf(numberingSystem);
const numberOptions = {
numberingSystem,
useGrouping: false
};
const one = new Intl.NumberFormat(locale, numberOptions).format(1);
const twoDigitOne = new Intl.NumberFormat(locale, {
...numberOptions,
minimumIntegerDigits: 2
}).format(1);
const partsOf = (ms) => {
const days = daysSinceEpoch(ms, timeZone, epoch);
if (!isAtRisk(days, ms, resolved.calendar)) return formatter.formatToParts(ms);
const moved = shiftedBy(ms, timeZone, kindOf(days));
if (moved === null) return formatter.formatToParts(ms);
return formatter.formatToParts(moved).map((part) => part.type === "year" ? {
...part,
value: [...part.value].length <= 2 ? twoDigitOne : one
} : part);
};
const rangeOf = (a, b) => {
const hooks = rangeHooks();
return (hooks ? hooks.checked(formatter, callerOptions, a, b) : null) ?? formatter.formatRange(a, b);
};
const repairedRange = (start, end) => {
const ends = [start, end];
const days = ends.map((ms) => daysSinceEpoch(ms, timeZone, epoch));
if (!days.some((day, at) => isAtRisk(day, ends[at] ?? 0, resolved.calendar))) return rangeOf(start, end);
const kinds = days.map(kindOf);
const moving = kinds.filter((kind) => kind !== 0).length;
const mixed = kinds.includes(1) && kinds.includes(-1);
const movedBy = (cycles) => {
const out = ends.map((ms, at) => kinds[at] === 0 ? ms : shiftedBy(ms, timeZone, kinds[at] * cycles));
return out[0] === null || out[1] === null ? null : [out[0], out[1]];
};
for (const cycles of TRIES) {
const first = movedBy(cycles);
const later = movedBy(cycles + 1);
if (first === null || later === null) return rangeOf(start, end);
const text = rangeOf(...first);
if (text === "") return "";
const rewritten = rewriteYears(text, rangeOf(...later), {
digitSet,
table,
one,
twoDigitOne
}, {
cycles,
moving,
mixed
});
if (rewritten !== null) return rewritten;
}
return "";
};
const standIn = {
format(date) {
return partsOf(toMilliseconds(date)).map((part) => part.value).join("");
},
formatToParts(date) {
return partsOf(toMilliseconds(date));
},
formatRange(start, end) {
return repairedRange(toMilliseconds(start), toMilliseconds(end));
},
formatRangeToParts() {
throw new TypeError("formatRangeToParts is not available on a formatter whose years are repaired (CORE-112)");
},
resolvedOptions() {
return resolved;
}
};
markRangeHandled(standIn);
return standIn;
}
export { epochTwin, repairIslamicEpochEra };