Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): read typed dates in every calendar (#9792)

nynexman44647be6b4644f98
diff --git a/.changeset/calendar-date-parser.md b/.changeset/calendar-date-parser.md
new file mode 100644
index 0000000000..1415c3aaf5
--- /dev/null
+++ b/.changeset/calendar-date-parser.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Core gains an internal parser for dates typed in a calendar system. It reads dates typed in any `CalendarSystem`, in any decimal digits, with month and era names, leap months such as Adar I, and Japanese eras such as `令和元年`, and returns a Gregorian date. A date the calendar does not have is rejected and never adjusted. It also writes the committed text and the format hint, and reads them back as the same date in each calendar's own locale, in English and Swedish, and in locales whose weekday names are also month or era names. No component reads typed text with it yet, and no public API changes. `Calendar` output does not change.
+
+@nynexman4464
diff --git a/docs/architecture/internationalization.md b/docs/architecture/internationalization.md
index 9f5c5f3abb..e4442ecf45 100644
--- a/docs/architecture/internationalization.md
+++ b/docs/architecture/internationalization.md
@@ -366,6 +366,7 @@ inferred from an implementation pull request.
- `packages/core/src/i18n/` — provider, context, public hooks, locale-direction
derivation, catalog types, and lookup/formatting runtime.
- `packages/core/src/utils/plainDate.ts`, `packages/core/src/utils/dateParser.ts`,
+ `packages/core/src/utils/calendarDateParser.ts`,
`packages/core/src/Timestamp/formatInstant.ts`,
`packages/core/src/Timestamp/formatRelativeTime.ts`,
`packages/core/src/PowerSearch/formatFilterValue.ts`,
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 12f4c270d1..813045a370 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -76,6 +76,9 @@ Approved implementations:
- `packages/core/src/PowerSearch/formatFilterValue.ts`
- `packages/core/src/NumberInput/numberParser.ts` — reads typed and pasted
numbers under the field's locale
+- `packages/core/src/utils/calendarDateParser.ts` — typed dates for DateInput
+ and DateTimeInput in any calendar: names, eras, field order, and digits read
+ off Intl and parsed back, the committed text, and the calendar's name
- `packages/core/src/utils/timeFormat.ts` — time-of-day text for TimeInput and
DateTimeInput: the locale's hour cycle, digits, separator, and day periods,
formatted and parsed back
diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.js b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
index 2f7f0fac6d..d00203f238 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.js
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
@@ -116,6 +116,10 @@ const APPROVED_IMPLEMENTATION_FILES = [
// NumberInput's locale-aware read of typed and pasted text: it derives the
// grouping/decimal separators and group sizes from Intl rather than a table.
'packages/core/src/NumberInput/numberParser.ts',
+ // DateInput/DateTimeInput typed dates in any calendar: month, era and
+ // weekday names, field order and digits read off Intl and parsed back, the
+ // committed text, and the calendar's display name.
+ 'packages/core/src/utils/calendarDateParser.ts',
// TimeInput/DateTimeInput time text: the locale's hour cycle, digits,
// separator and day-period words, read off Intl and parsed back.
'packages/core/src/utils/timeFormat.ts',
diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
index 1d09ef1c74..036fafcfa4 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
@@ -40,6 +40,8 @@ const RELATIVE_TIME_INFRA_FILE =
const NUMBER_PARSER_INFRA_FILE =
'packages/core/src/NumberInput/numberParser.ts';
const TIME_FORMAT_INFRA_FILE = 'packages/core/src/utils/timeFormat.ts';
+const CALENDAR_DATE_PARSER_INFRA_FILE =
+ 'packages/core/src/utils/calendarDateParser.ts';
const NUMBER_PARSER_TEST_ORACLE_FILE =
'packages/core/src/NumberInput/numberParser.test.ts';
const NUMBER_PARSER_DOCBLOCK_ORACLE_FILE =
@@ -148,6 +150,18 @@ tester.run('no-raw-intl-locale', rule, {
code: `new Intl.DateTimeFormat(locale, {hour: 'numeric'}).resolvedOptions();`,
filename: TIME_FORMAT_INFRA_FILE,
},
+ {
+ code: `new Intl.DateTimeFormat(locale, {calendar, timeZone: 'UTC'}).formatToParts(ms);`,
+ filename: CALENDAR_DATE_PARSER_INFRA_FILE,
+ },
+ {
+ code: `new Intl.DisplayNames(locale, {type: 'calendar'}).of(calendar);`,
+ filename: CALENDAR_DATE_PARSER_INFRA_FILE,
+ },
+ {
+ code: `text.toLocaleLowerCase(locale);`,
+ filename: CALENDAR_DATE_PARSER_INFRA_FILE,
+ },
// -- Named test-oracle files retain meaningful explicit-locale fixtures. --
{
code: `number.toLocaleString('en-US');`,
@@ -285,6 +299,22 @@ tester.run('no-raw-intl-locale', rule, {
filename: TIME_FORMAT_INFRA_FILE,
errors: [ambientIntlInImplementation],
},
+ {
+ code: `new Intl.DateTimeFormat(undefined, {calendar: 'persian'});`,
+ filename: CALENDAR_DATE_PARSER_INFRA_FILE,
+ errors: [ambientIntlInImplementation],
+ },
+ {
+ code: `text.toLocaleLowerCase();`,
+ filename: CALENDAR_DATE_PARSER_INFRA_FILE,
+ errors: [ambientIntlInImplementation],
+ },
+ {
+ // The helper is approved only at its own path.
+ code: `new Intl.DateTimeFormat(locale, {calendar}).formatToParts(ms);`,
+ filename: 'packages/core/src/DateInput/calendarDateParser.ts',
+ errors: [rawIntlLocale],
+ },
{
code: `new Intl.RelativeTimeFormat();`,
filename: RELATIVE_TIME_INFRA_FILE,
diff --git a/packages/core/src/utils/calendarDateParser.roundtrip.test.ts b/packages/core/src/utils/calendarDateParser.roundtrip.test.ts
new file mode 100644
index 0000000000..9737b031b3
--- /dev/null
+++ b/packages/core/src/utils/calendarDateParser.roundtrip.test.ts
@@ -0,0 +1,128 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file calendarDateParser.roundtrip.test.ts
+ * @input Uses vitest, temporal-polyfill, calendarDateParser, calendarSystem
+ * @output Round-trip matrix: every calendar's committed text and format hint
+ * in its native locale and others reads back as the same date
+ * @position Testing; samples 1900 through 2100 for calendarDateParser.ts
+ */
+
+import {afterAll, beforeAll, describe, expect, it} from 'vitest';
+import {Temporal as TemporalPolyfill} from 'temporal-polyfill/full';
+import {
+ formatCalendarDateText,
+ formatCalendarDateHint,
+ getCalendarDateLexicon,
+ parseCalendarDate,
+} from './calendarDateParser';
+import type {CalendarSystem} from './calendarSystem';
+import {plainDateAddDays, plainDateDiffDays} from './plainDate';
+import type {PlainDate} from './dateTypes';
+
+const host = globalThis as {Temporal?: unknown};
+const hadTemporal = host.Temporal != null;
+beforeAll(() => {
+ host.Temporal ??= TemporalPolyfill;
+});
+afterAll(() => {
+ if (!hadTemporal) {
+ delete host.Temporal;
+ }
+});
+
+const NATIVE_LOCALES: Readonly<Record<CalendarSystem, string>> = {
+ gregory: 'en-GB',
+ iso8601: 'en-CA',
+ buddhist: 'th-TH',
+ roc: 'zh-TW',
+ japanese: 'ja-JP',
+ persian: 'fa-IR',
+ indian: 'hi-IN',
+ hebrew: 'he',
+ chinese: 'zh-CN',
+ dangi: 'ko-KR',
+ coptic: 'ar-EG',
+ ethiopic: 'am-ET',
+ ethioaa: 'am-ET',
+ 'islamic-civil': 'ar-EG',
+ 'islamic-tbla': 'ar',
+ 'islamic-umalqura': 'ar-SA',
+};
+
+// Weekday words that name months or eras, digit month names, cycle years.
+const MORE_LOCALES: Partial<Record<CalendarSystem, string>> = {
+ gregory: 'fr-FR it-IT es-ES ro-RO vi-VN',
+ buddhist: 'fr-FR',
+ roc: 'de-DE',
+ japanese: 'it-IT hu-HU',
+ persian: 'nb-NO',
+ chinese: 'ca-ES cs-CZ de-DE fi-FI fr-FR it-IT nl-NL pl-PL pt-PT ru-RU',
+ dangi: 'pt-BR fi-FI',
+ ethiopic: 'pt-BR',
+ 'islamic-civil': 'fr-FR hu-HU sr-RS',
+};
+
+// Text in the lunisolar calendars costs far more to compose under the
+// polyfill, so those calendars sample fewer days. Each locale starts on another weekday.
+const FIRST = {year: 1900, month: 1, day: 1};
+const DAYS = plainDateDiffDays(FIRST, {year: 2100, month: 12, day: 31});
+const TODAY = {year: 2026, month: 11, day: 2};
+
+function sampleDays(step: number, offset: number): PlainDate[] {
+ const days: PlainDate[] = [];
+ for (let day = offset; day <= DAYS; day += step) {
+ days.push(plainDateAddDays(FIRST, day));
+ }
+ return days;
+}
+
+function failures(
+ locale: string,
+ calendar: CalendarSystem,
+ step: number,
+ offset: number,
+) {
+ const lexicon = getCalendarDateLexicon(locale, calendar);
+ const failed: string[] = [];
+ for (const date of sampleDays(step, offset)) {
+ const texts = [
+ formatCalendarDateHint(date, locale, calendar),
+ formatCalendarDateText(date, 'date', locale, calendar),
+ formatCalendarDateText(date, 'date_long', locale, calendar),
+ formatCalendarDateText(date, 'date_weekday', locale, calendar),
+ ];
+ for (const text of texts) {
+ const result = parseCalendarDate(text, lexicon, {today: TODAY});
+ const isSame =
+ result.kind === 'value' &&
+ result.date.year === date.year &&
+ result.date.month === date.month &&
+ result.date.day === date.day;
+ if (!isSame && failed.length < 5) {
+ failed.push(`${JSON.stringify(text)} -> ${JSON.stringify(result)}`);
+ }
+ }
+ }
+ return failed;
+}
+
+describe('committed text reads back as the same date (FR13)', () => {
+ for (const [calendar, native] of Object.entries(NATIVE_LOCALES) as [
+ CalendarSystem,
+ string,
+ ][]) {
+ const isLunisolar = calendar === 'chinese' || calendar === 'dangi';
+ it(`${calendar} in ${native}, en, and sv-SE`, () => {
+ const step = isLunisolar ? 42 : 14;
+ expect(failures(native, calendar, step, 0)).toEqual([]);
+ expect(failures('en', calendar, step * 3, 2)).toEqual([]);
+ expect(failures('sv-SE', calendar, step * 3, 4)).toEqual([]);
+ });
+ }
+ it.each(Object.entries(MORE_LOCALES))('%s in %s', (calendar, locales) => {
+ for (const locale of locales.split(' ')) {
+ expect(failures(locale, calendar as CalendarSystem, 997, 1)).toEqual([]);
+ }
+ });
+});
diff --git a/packages/core/src/utils/calendarDateParser.test.ts b/packages/core/src/utils/calendarDateParser.test.ts
new file mode 100644
index 0000000000..34f353db22
--- /dev/null
+++ b/packages/core/src/utils/calendarDateParser.test.ts
@@ -0,0 +1,373 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file calendarDateParser.test.ts
+ * @input Uses vitest, temporal-polyfill, calendarDateParser
+ * @output Unit tests for typed dates in every calendar: reading, years,
+ * rejection kinds, completeness, committed text, and the format hint
+ * @position Testing; validates calendarDateParser.ts
+ */
+
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+} from 'vitest';
+import {Temporal as TemporalPolyfill} from 'temporal-polyfill/full';
+import {
+ type CalendarDateParseOptions,
+ type CalendarDateParseResult,
+ calendarDisplayName,
+ formatCalendarDateText,
+ formatCalendarDateHint,
+ getCalendarDateLexicon,
+ parseCalendarDate,
+} from './calendarDateParser';
+import type {CalendarSystem} from './calendarSystem';
+import {formatSharedDate} from './plainDate';
+
+const host = globalThis as {Temporal?: unknown};
+const hadTemporal = host.Temporal != null;
+beforeAll(() => {
+ host.Temporal ??= TemporalPolyfill;
+});
+afterAll(() => {
+ if (!hadTemporal) {
+ delete host.Temporal;
+ }
+});
+
+const TODAY = {year: 2026, month: 11, day: 2};
+
+function parse(
+ locale: string,
+ calendar: CalendarSystem,
+ text: string,
+ options: CalendarDateParseOptions = {},
+): CalendarDateParseResult {
+ return parseCalendarDate(text, getCalendarDateLexicon(locale, calendar), {
+ today: TODAY,
+ ...options,
+ });
+}
+
+/** The ISO date a text reads as, or the result kind when it is not a date. */
+function iso(locale: string, calendar: CalendarSystem, text: string): string {
+ const result = parse(locale, calendar, text);
+ if (result.kind !== 'value') {
+ return result.kind;
+ }
+ const {year, month, day} = result.date;
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
+}
+
+function complete(locale: string, calendar: CalendarSystem, text: string) {
+ const result = parse(locale, calendar, text);
+ return 'isComplete' in result ? result.isComplete : result.kind;
+}
+
+describe('reading dates written in the calendar (FR9)', () => {
+ it('reads any Unicode decimal digits, in mixed scripts', () => {
+ expect(iso('fa-IR', 'persian', '۱۴۰۵/۸/۱۱')).toBe('2026-11-02');
+ expect(iso('fa-IR', 'persian', '١٤٠٥/٨/١١')).toBe('2026-11-02');
+ expect(iso('fa-IR', 'persian', '۱۴۰۵/8/١١')).toBe('2026-11-02');
+ expect(iso('hi-IN', 'indian', '११/८/१९४८ शक')).toBe('2026-11-02');
+ });
+
+ it('ignores bidirectional marks', () => {
+ expect(
+ iso('ar-SA', 'islamic-umalqura', '\u200f٢٢\u200f/٥\u200f/١٤٤٨ هـ'),
+ ).toBe('2026-11-02');
+ expect(iso('ar-SA', 'islamic-umalqura', '\u202b٢٢/٥/١٤٤٨ هـ\u202c')).toBe(
+ '2026-11-02',
+ );
+ });
+
+ it('reads an apostrophe for the ʻ of Islamic month names', () => {
+ for (const mark of ["'", '`', '\u2019', '\u02bb']) {
+ expect(
+ iso('en', 'islamic-umalqura', `Dhu${mark}l-Hijjah 10, 1447 AH`),
+ ).toBe('2026-05-27');
+ }
+ });
+
+ it("follows the locale's numeric field order", () => {
+ expect(iso('fa-IR', 'persian', '1405/8/11')).toBe('2026-11-02');
+ expect(iso('en-US', 'persian', '8/11/1405')).toBe('2026-11-02');
+ expect(iso('he', 'hebrew', '22/2/5787')).toBe('2026-11-02');
+ expect(iso('en-GB', 'gregory', '12/01/2026')).toBe('2026-01-12');
+ expect(iso('en-US', 'gregory', '12/01/2026')).toBe('2026-12-01');
+ });
+
+ it('reads a number of three or more digits beside a month name as the year', () => {
+ expect(iso('fa-IR', 'persian', '۱۱ آبان ۱۴۰۵')).toBe('2026-11-02');
+ expect(iso('fa-IR', 'persian', '۱۴۰۵ آبان ۱۱')).toBe('2026-11-02');
+ expect(iso('en-US', 'gregory', '2026 Nov 2')).toBe('2026-11-02');
+ });
+
+ it('reads month and era names of the locale and English, in every width', () => {
+ expect(iso('fa-IR', 'persian', '11 Aban 1405')).toBe('2026-11-02');
+ expect(iso('en-US', 'persian', 'Aban 11, 1405 AP')).toBe('2026-11-02');
+ expect(iso('th-TH', 'buddhist', '2 พ.ย. 2569')).toBe('2026-11-02');
+ expect(iso('th-TH', 'buddhist', '2 พฤศจิกายน พ.ศ. 2569')).toBe(
+ '2026-11-02',
+ );
+ expect(iso('ja-JP', 'japanese', 'R8/11/2')).toBe('2026-11-02');
+ expect(iso('ja-JP', 'japanese', 'Reiwa 8/11/2')).toBe('2026-11-02');
+ expect(iso('de-DE', 'gregory', 'Mo., 2. Nov. 2026')).toBe('2026-11-02');
+ // A weekday word that is also a month name.
+ expect(iso('fr-FR', 'gregory', 'mar. 3 nov. 2026')).toBe('2026-11-03');
+ expect(iso('it-IT', 'gregory', 'mar 3 mar 2026')).toBe('2026-03-03');
+ expect(iso('vi-VN', 'gregory', 'Thứ 3, 3 thg 11, 2026')).toBe('2026-11-03');
+ });
+
+ it('ignores case and Latin diacritics', () => {
+ expect(iso('en-US', 'japanese', 'Jan 7, 64 Shōwa')).toBe('1989-01-07');
+ expect(iso('en-US', 'japanese', 'JAN 7, 64 showa')).toBe('1989-01-07');
+ });
+
+ it('reads an abbreviation that starts only one month name', () => {
+ expect(iso('en-US', 'gregory', 'Sept 1, 2026')).toBe('2026-09-01');
+ expect(iso('en-US', 'gregory', 'Ma 1, 2026')).toBe('unreadable');
+ });
+
+ it('reads Hebrew month numbers as positions in the typed year', () => {
+ expect(iso('he', 'hebrew', '1/6/5784')).toBe('2024-02-10');
+ expect(iso('he', 'hebrew', '1/7/5784')).toBe('2024-03-11');
+ expect(iso('he', 'hebrew', '1/6/5785')).toBe('2025-03-01');
+ });
+
+ it('reads a plain Adar in a Hebrew leap year as Adar II', () => {
+ expect(iso('en-US', 'hebrew', '1 Adar 5784')).toBe('2024-03-11');
+ expect(iso('en-US', 'hebrew', '1 Adar II 5784')).toBe('2024-03-11');
+ expect(iso('en-US', 'hebrew', '1 Adar I 5784')).toBe('2024-02-10');
+ expect(iso('he', 'hebrew', '1 אדר 5784')).toBe('2024-03-11');
+ expect(iso('he', 'hebrew', '1 אדר 5785')).toBe('2025-03-01');
+ });
+
+ it('reads Hebrew month names with the ב prefix and a typed apostrophe', () => {
+ expect(iso('he', 'hebrew', '22 בחשוון 5787')).toBe('2026-11-02');
+ expect(iso('he', 'hebrew', "1 אדר א' 5784")).toBe('2024-02-10');
+ });
+
+ it('reads month numbers of the Chinese and Dangi calendars with the leap marker', () => {
+ expect(iso('zh-CN', 'chinese', '2025年闰六月1')).toBe('2025-07-25');
+ expect(iso('zh-CN', 'chinese', '2025年六月1')).toBe('2025-06-25');
+ expect(iso('zh-CN', 'chinese', '2025/6/1')).toBe('2025-06-25');
+ expect(iso('ko-KR', 'dangi', '2025. 윤6. 1.')).toBe('2025-07-25');
+ expect(iso('ko-KR', 'dangi', '2025. 6. 1.')).toBe('2025-06-25');
+ });
+
+ it('rejects traditional numerals', () => {
+ expect(iso('zh-CN', 'chinese', '2026丙午年九月廿四')).toBe('unreadable');
+ expect(iso('he', 'hebrew', 'כ״ב בחשוון תשפ״ז')).toBe('unreadable');
+ });
+
+ it('rejects mixed separators between numbers', () => {
+ expect(iso('en-US', 'gregory', '1/25.2026')).toBe('unreadable');
+ });
+
+ it('reads ISO-shaped text as calendar fields, and as ISO for system_date', () => {
+ expect(iso('sv-SE', 'persian', '1405-08-11 AP')).toBe('2026-11-02');
+ expect(iso('en-US', 'persian', '1405-08-11')).toBe('2026-11-02');
+ const result = parse('en-US', 'persian', '2026-11-02', {
+ isoIsGregorian: true,
+ });
+ expect(result).toEqual({
+ kind: 'value',
+ date: TODAY,
+ isComplete: true,
+ });
+ });
+});
+
+describe('years of the calendar (FR10)', () => {
+ it('reads a Buddhist year literally', () => {
+ expect(iso('th-TH', 'buddhist', '2/11/2569')).toBe('2026-11-02');
+ expect(iso('th-TH', 'buddhist', '2/11/2026')).toBe('1483-11-02');
+ });
+
+ it('reads Japanese years in the current era or as Gregorian years', () => {
+ expect(iso('ja-JP', 'japanese', '8/11/25')).toBe('2026-11-25');
+ expect(iso('ja-JP', 'japanese', '2026/11/2')).toBe('2026-11-02');
+ expect(iso('ja-JP', 'japanese', '令和元年5月1日')).toBe('2019-05-01');
+ });
+
+ it('rejects a Japanese era year outside its era', () => {
+ expect(iso('ja-JP', 'japanese', '平成31年4月30日')).toBe('2019-04-30');
+ expect(iso('ja-JP', 'japanese', '平成31年5月1日')).toBe('nonexistent');
+ expect(iso('ja-JP', 'japanese', '令和1年4月30日')).toBe('nonexistent');
+ expect(iso('ja-JP', 'japanese', 'S64/1/8')).toBe('nonexistent');
+ expect(iso('en-US', 'japanese', 'May 1, 31 Heisei')).toBe('nonexistent');
+ });
+
+ it('reads Minguo calendar years of up to three digits in the 民國 era', () => {
+ expect(iso('zh-TW', 'roc', '115/11/2')).toBe('2026-11-02');
+ expect(iso('zh-TW', 'roc', '民國115/11/2')).toBe('2026-11-02');
+ expect(iso('zh-TW', 'roc', '民國前12年1月1日')).toBe('1900-01-01');
+ });
+
+ it('reads Ethiopic years in the AM era unless AA is typed', () => {
+ expect(iso('am-ET', 'ethiopic', '23/2/2019')).toBe('2026-11-02');
+ expect(iso('am-ET', 'ethiopic', '1/1/7519 AA')).toBe('2026-09-11');
+ });
+
+ it('resolves a two-digit year within 80 years before and 19 after', () => {
+ expect(iso('en-US', 'gregory', '1/2/45')).toBe('2045-01-02');
+ expect(iso('en-US', 'gregory', '1/2/46')).toBe('1946-01-02');
+ expect(iso('th-TH', 'buddhist', '2/11/69')).toBe('2026-11-02');
+ expect(iso('fa-IR', 'persian', '05/8/11')).toBe('2026-11-02');
+ });
+
+ it('shows the era in the hint and the committed text', () => {
+ expect(formatCalendarDateHint(TODAY, 'th-TH', 'buddhist')).toContain(
+ 'พ.ศ.',
+ );
+ expect(
+ formatCalendarDateText(TODAY, 'date_long', 'th-TH', 'buddhist'),
+ ).toBe('2 พฤศจิกายน พ.ศ. 2569');
+ expect(formatCalendarDateHint(TODAY, 'zh-TW', 'roc')).toContain('民國');
+ expect(formatCalendarDateText(TODAY, 'date', 'zh-TW', 'roc')).toContain(
+ '民國',
+ );
+ });
+});
+
+describe('rejection kinds (FR11, AR3)', () => {
+ it('reports dates the calendar does not have, without adjusting them', () => {
+ expect(iso('fa-IR', 'persian', '1404/12/30')).toBe('nonexistent');
+ expect(iso('fa-IR', 'persian', '1403/12/30')).toBe('2025-03-20');
+ expect(iso('en-US', 'hebrew', '1 Adar I 5785')).toBe('nonexistent');
+ expect(iso('am-ET', 'ethiopic', '6/13/2016')).toBe('nonexistent');
+ expect(iso('am-ET', 'ethiopic', '6/13/2015')).toBe('2023-09-11');
+ expect(iso('ar-SA', 'islamic-umalqura', '30/1/1448')).toBe('nonexistent');
+ expect(iso('zh-CN', 'chinese', '2026年闰六月1')).toBe('nonexistent');
+ expect(iso('en-US', 'gregory', '2/30/2026')).toBe('nonexistent');
+ });
+
+ it('reports unreadable text and part of a date apart', () => {
+ expect(iso('en-US', 'gregory', 'not a date')).toBe('unreadable');
+ expect(iso('en-US', 'gregory', '25/1/2026')).toBe('unreadable');
+ expect(iso('en-US', 'gregory', 'No')).toBe('incomplete');
+ expect(iso('fa-IR', 'persian', '۱۴۰۵/۸')).toBe('incomplete');
+ expect(iso('en-US', 'gregory', ' ')).toBe('empty');
+ });
+
+ it('reports a date the constraints reject as out of range', () => {
+ const result = parse('fa-IR', 'persian', '1405/8/11', {
+ isDateDisabled: date => date.year === 2026,
+ });
+ expect(result).toEqual({kind: 'outOfRange', date: TODAY, isComplete: true});
+ });
+});
+
+describe('complete input (FR12)', () => {
+ it('reports only the finished text of a day-first numeric date as complete', () => {
+ const typed = '12/01/2026';
+ const states = [...typed].map((_, i) => {
+ const text = typed.slice(0, i + 1);
+ const result = parse('en-GB', 'gregory', text);
+ return result.kind === 'value' && result.isComplete ? text : null;
+ });
+ expect(states.filter(Boolean)).toEqual(['12/01/2026']);
+ });
+
+ it('leaves two-digit years and omitted years for Enter or blur', () => {
+ expect(complete('en-GB', 'gregory', '12/01/90')).toBe(false);
+ expect(iso('en-GB', 'gregory', '12/01/90')).toBe('1990-01-12');
+ expect(complete('en-US', 'gregory', 'Jan 25')).toBe(false);
+ expect(iso('en-US', 'gregory', 'Jan 25')).toBe('2026-01-25');
+ });
+
+ it('waits while a separator trails or the last field can take a digit', () => {
+ expect(complete('en-US', 'gregory', '11/2/2026/')).toBe(false);
+ expect(complete('fa-IR', 'persian', '1405/8/3')).toBe(false);
+ expect(complete('fa-IR', 'persian', '1405/8/4')).toBe(true);
+ expect(complete('ja-JP', 'japanese', '令和8年11月2')).toBe(false);
+ expect(complete('ja-JP', 'japanese', '令和8年11月2日')).toBe(true);
+ expect(complete('ko-KR', 'dangi', '2026. 9. 2')).toBe(false);
+ expect(complete('ko-KR', 'dangi', '2026. 9. 2.')).toBe(true);
+ // A 3 can start a 30 that the month lacks.
+ expect(complete('fa-IR', 'persian', '1404/12/3')).toBe(false);
+ expect(complete('sv-SE', 'gregory', '2026-02-3')).toBe(false);
+ });
+
+ it('counts an era year with its era as a complete year', () => {
+ expect(complete('ja-JP', 'japanese', '令和8年11月25日')).toBe(true);
+ expect(complete('en-US', 'japanese', 'November 25, 8 Reiwa')).toBe(true);
+ });
+});
+
+describe('committed text (FR13)', () => {
+ it('keeps Gregorian text identical to the shared date formats', () => {
+ for (const format of ['date', 'date_long', 'date_weekday'] as const) {
+ expect(formatCalendarDateText(TODAY, format, 'en-US', 'gregory')).toBe(
+ formatSharedDate(TODAY, format, 'en-US'),
+ );
+ }
+ });
+
+ it('keeps system_date ISO in every calendar', () => {
+ expect(
+ formatCalendarDateText(TODAY, 'system_date', 'fa-IR', 'persian'),
+ ).toBe('2026-11-02');
+ });
+
+ it('writes the named formats in the calendar', () => {
+ expect(formatCalendarDateText(TODAY, 'date_long', 'en-US', 'persian')).toBe(
+ 'Aban 11, 1405 AP',
+ );
+ expect(formatCalendarDateText(TODAY, 'date_long', 'en-US', 'hebrew')).toBe(
+ '22 Heshvan 5787 AM',
+ );
+ });
+
+ it.each(['de-DE', 'ja'])('writes Chinese and Dangi years in %s', locale => {
+ for (const calendar of ['chinese', 'dangi'] as const) {
+ const text = formatCalendarDateText(TODAY, 'date_long', locale, calendar);
+ expect(text).toContain('2026');
+ expect(iso(locale, calendar, text)).toBe('2026-11-02');
+ }
+ });
+
+ it('writes the format hint in the numeric pattern', () => {
+ expect(formatCalendarDateHint(TODAY, 'fa-IR', 'persian')).toBe('۱۴۰۵/۸/۱۱');
+ expect(formatCalendarDateHint(TODAY, 'en-US', 'gregory')).toBe('11/2/2026');
+ });
+});
+
+describe('calendar names (AR2)', () => {
+ it('names the calendar in the locale', () => {
+ expect(calendarDisplayName('persian', 'en')).toBe('Persian Calendar');
+ expect(calendarDisplayName('hebrew', 'he')).toBe('לוח השנה העברי');
+ });
+});
+
+describe('without Temporal', () => {
+ let saved: unknown;
+ beforeEach(() => {
+ saved = host.Temporal;
+ delete host.Temporal;
+ });
+ afterEach(() => {
+ host.Temporal = saved;
+ });
+
+ it('reads Buddhist, Minguo, and Japanese dates', () => {
+ expect(iso('th', 'buddhist', '2/11/2569')).toBe('2026-11-02');
+ expect(iso('zh-Hant', 'roc', '民國115/11/2')).toBe('2026-11-02');
+ expect(iso('ja', 'japanese', '令和8年11月2日')).toBe('2026-11-02');
+ expect(iso('ja', 'japanese', '平成31年5月1日')).toBe('nonexistent');
+ });
+
+ it('reads Gregorian dates where a calendar needs Temporal', () => {
+ expect(iso('en', 'persian', 'November 2, 2026')).toBe('2026-11-02');
+ expect(formatCalendarDateText(TODAY, 'date_long', 'en', 'persian')).toBe(
+ 'November 2, 2026',
+ );
+ });
+});
diff --git a/packages/core/src/utils/calendarDateParser.ts b/packages/core/src/utils/calendarDateParser.ts
new file mode 100644
index 0000000000..f49f7d2e9b
--- /dev/null
+++ b/packages/core/src/utils/calendarDateParser.ts
@@ -0,0 +1,1295 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file calendarDateParser.ts
+ * @input Date text, locale, calendar; Intl, calendarSystem, unicodeDigits
+ * @output Cached per-locale lexicons, a typed-date parser with distinct rejection
+ * kinds, committed display text, the format hint, and calendar display names
+ * @position Core utility; reads and writes dates typed in a calendar system
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/utils/calendarDateParser.test.ts
+ * - /packages/core/src/utils/calendarDateParser.roundtrip.test.ts
+ */
+
+import type {PlainDate} from './dateTypes';
+import type {Locale} from '../i18n/types';
+import {
+ type CalendarSystem,
+ type CalendarDateFields,
+ calendarDateFromFields,
+ calendarMonthOf,
+ calendarMonthsInYear,
+ formatCalendarDate,
+ isCalendarSystemAvailable,
+ isGregorianAligned,
+} from './calendarSystem';
+import {
+ type SharedDateFormat,
+ SHARED_DATE_FORMAT_OPTIONS,
+ formatSharedDate,
+ getDaysInMonth,
+ plainDateAddDays,
+ plainDateDiffDays,
+ plainDateFormat,
+ plainDateFormatToParts,
+ plainDateToday,
+} from './plainDate';
+import {INVISIBLE_CHARS, toAsciiDigits} from './unicodeDigits';
+
+/** How a typed text reads in a calendar. */
+export type CalendarDateParseResult =
+ | {readonly kind: 'empty'}
+ /** Part of a date: nothing to report yet. */
+ | {readonly kind: 'incomplete'}
+ /** Text that cannot become a date. */
+ | {readonly kind: 'unreadable'}
+ /** A readable date that the calendar does not have. */
+ | {readonly kind: 'nonexistent'; readonly isComplete: boolean}
+ /** A date that the constraints reject. */
+ | {
+ readonly kind: 'outOfRange';
+ readonly date: PlainDate;
+ readonly isComplete: boolean;
+ }
+ /**
+ * A date. `isComplete` is true when more typing cannot change its meaning,
+ * so a field may report it while the person types.
+ */
+ | {
+ readonly kind: 'value';
+ readonly date: PlainDate;
+ readonly isComplete: boolean;
+ };
+
+export interface CalendarDateParseOptions {
+ /** The Gregorian date that two-digit and omitted years resolve against. */
+ readonly today?: PlainDate;
+ /** Reads ISO-shaped text as a Gregorian ISO date, as `system_date` shows. */
+ readonly isoIsGregorian?: boolean;
+ /** Returns true for a date that may not be chosen. */
+ readonly isDateDisabled?: (date: PlainDate) => boolean;
+}
+
+type DateField = 'year' | 'month' | 'day';
+
+interface EraArithmetic {
+ /** The Gregorian year before era year 1, or after it for a backward era. */
+ readonly base: number;
+ readonly isForward: boolean;
+}
+
+/** What a locale writes for one calendar, learned from Intl. */
+export interface CalendarDateLexicon {
+ readonly locale: Locale;
+ readonly calendar: CalendarSystem;
+ readonly order: ReadonlyArray<DateField>;
+ readonly nameOrder: ReadonlyArray<DateField>;
+ readonly months: ReadonlyMap<string, ReadonlySet<string>>;
+ readonly monthTemplates: ReadonlyArray<MonthTemplate>;
+ readonly leapMarkers: ReadonlySet<string>;
+ readonly eras: ReadonlyMap<string, string>;
+ readonly yearAliases: ReadonlyMap<string, string>;
+ readonly trailers: ReadonlySet<string>;
+ readonly weekdays: ReadonlySet<string>;
+ readonly vocabulary: ReadonlyArray<string>;
+ readonly vocabularySet: ReadonlySet<string>;
+ readonly isNumericMonthOrdinal: boolean;
+ readonly eraArithmetic: ReadonlyMap<string, EraArithmetic>;
+}
+
+interface MonthTemplate {
+ readonly pre: string;
+ readonly post: string;
+ readonly isLeap: boolean;
+}
+
+const NUMERIC: Intl.DateTimeFormatOptions = {
+ year: 'numeric',
+ month: 'numeric',
+ day: 'numeric',
+};
+const LONG = SHARED_DATE_FORMAT_OPTIONS.date_long;
+const YEAR_ONLY: Intl.DateTimeFormatOptions = {year: 'numeric'};
+const ERA_AND_YEAR: Intl.DateTimeFormatOptions = {
+ era: 'short',
+ year: 'numeric',
+};
+const LONG_WITH_ERA: Intl.DateTimeFormatOptions = {...LONG, era: 'long'};
+const ERA_WIDTHS: Readonly<Record<string, Intl.DateTimeFormatOptions>> = {
+ long: {era: 'long', year: 'numeric'},
+ short: ERA_AND_YEAR,
+ narrow: {era: 'narrow', year: 'numeric'},
+};
+const WEEKDAY_FORMATS: ReadonlyArray<Intl.DateTimeFormatOptions> = [
+ {weekday: 'long'},
+ {weekday: 'short'},
+ {...LONG, weekday: 'long'},
+ {...LONG, weekday: 'short'},
+];
+const LONG_WITH_WEEKDAY: Intl.DateTimeFormatOptions = {
+ ...LONG,
+ weekday: 'short',
+};
+// Built at runtime: the Babel copy in a Next.js source build rejects a
+// `\p{...}` regex literal.
+const LETTER = new RegExp('[\\p{L}\\p{M}]', 'u');
+const SEPARATOR = new RegExp('[\\p{P}\\p{S}]', 'u');
+const ONLY_SEPARATORS = new RegExp('^[\\p{P}\\p{S}]+$', 'u');
+const NOT_WORDS = new RegExp('[\\d\\p{P}\\p{S}]+', 'gu');
+const LATIN_MARKS = new RegExp('(\\p{Script=Latin})\\p{Mn}+', 'gu');
+// Scripts written without spaces between words: a name may run into the
+// next word, so a name match there needs no word boundary.
+const SPACELESS = new RegExp(
+ '[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\p{Script=Thai}\\p{Script=Lao}\\p{Script=Khmer}\\p{Script=Myanmar}]',
+ 'u',
+);
+const LUNISOLAR: ReadonlySet<CalendarSystem> = new Set(['chinese', 'dangi']);
+const WITHOUT_ERA: ReadonlySet<CalendarSystem> = new Set([
+ 'gregory',
+ 'iso8601',
+ 'chinese',
+ 'dangi',
+]);
+
+/**
+ * One ISO date inside each era of a calendar. Intl supplies the names; the
+ * era codes are the Temporal and ECMA-402 identifiers.
+ */
+const ERA_SAMPLES: Readonly<Record<string, Readonly<Record<string, string>>>> =
+ {
+ gregory: {ce: '2000-06-15', bce: '-000100-06-15'},
+ japanese: {
+ meiji: '1900-06-15',
+ taisho: '1920-06-15',
+ showa: '1950-06-15',
+ heisei: '2000-06-15',
+ reiwa: '2026-06-15',
+ },
+ roc: {roc: '2026-06-15', broc: '1900-06-15'},
+ buddhist: {be: '2026-06-15'},
+ ethiopic: {am: '2026-06-15', aa: '-005600-06-15'},
+ ethioaa: {aa: '2026-06-15'},
+ coptic: {am: '2026-06-15'},
+ persian: {ap: '2026-06-15'},
+ hebrew: {am: '2026-06-15'},
+ indian: {shaka: '2026-06-15'},
+ 'islamic-umalqura': {ah: '2026-06-15'},
+ 'islamic-civil': {ah: '2026-06-15'},
+ 'islamic-tbla': {ah: '2026-06-15'},
+ };
+
+/** The calendar a text field reads and writes. `iso8601` writes as Gregorian. */
+function textCalendar(calendar: CalendarSystem): CalendarSystem {
+ if (calendar === 'iso8601' || !isCalendarSystemAvailable(calendar)) {
+ return 'gregory';
+ }
+ return calendar;
+}
+
+// =============================================================================
+// Intl access
+// =============================================================================
+
+/** Part types such as `relatedYear` and `yearName` are absent from older TS libs. */
+function partType(part: Intl.DateTimeFormatPart): string {
+ return part.type;
+}
+
+function isoToPlainDate(iso: string): PlainDate {
+ const match = /^(-?\d+)-(\d+)-(\d+)$/.exec(iso);
+ if (match == null) {
+ throw new RangeError(`Bad sample date ${iso}`);
+ }
+ return {year: +match[1], month: +match[2], day: +match[3]};
+}
+
+function partsOf(
+ locale: Locale,
+ calendar: CalendarSystem,
+ options: Intl.DateTimeFormatOptions,
+ pd: PlainDate,
+): Intl.DateTimeFormatPart[] {
+ return plainDateFormatToParts(pd, {...options, calendar}, locale);
+}
+
+// =============================================================================
+// Normalization
+// =============================================================================
+
+/** Text in one comparable form: ASCII digits, lower case, no Latin accents. */
+export function normalizeDateText(text: string, locale: Locale): string {
+ // Most typed text is printable ASCII; skip the Unicode passes it does not need.
+ if (/^[\u0020-\u007e]*$/.test(text)) {
+ const ascii = text.replaceAll('`', "'");
+ return /[A-Z]/.test(ascii) ? ascii.toLocaleLowerCase(locale) : ascii;
+ }
+ const folded = text
+ .normalize('NFKC')
+ .replace(INVISIBLE_CHARS, '')
+ // Pasted text can carry bidi embeddings.
+ .replace(/[\u202a-\u202e]/g, '')
+ // People type an ASCII apostrophe or quote for Hebrew geresh and
+ // gershayim, and for the ʻ of Islamic month names such as Dhuʻl-Hijjah.
+ .replace(/[\u05f3\u2018\u2019\u02bb\u02bc\u02bf`]/g, "'")
+ .replace(/[\u05f4\u201c\u201d]/g, '"');
+ let result = (toAsciiDigits(folded) ?? folded).toLocaleLowerCase(locale);
+ if (/[\u00c0-\u024f\u1e00-\u1eff]/.test(result)) {
+ // Fold Latin accents only: in other scripts a mark is part of the letter.
+ result = result
+ .normalize('NFD')
+ .replace(LATIN_MARKS, '$1')
+ .normalize('NFC');
+ }
+ return result;
+}
+
+// =============================================================================
+// Lexicon
+// =============================================================================
+
+const lexicons = new Map<string, CalendarDateLexicon>();
+
+/**
+ * The lexicon for a locale and calendar, built on first use and cached.
+ * Building one formats a few hundred dates; call it when a field gains focus.
+ */
+export function getCalendarDateLexicon(
+ locale: Locale,
+ calendar: CalendarSystem,
+): CalendarDateLexicon {
+ const resolved = textCalendar(calendar);
+ const key = `${locale}|${resolved}`;
+ let lexicon = lexicons.get(key);
+ if (lexicon == null) {
+ lexicon = buildLexicon(locale, resolved);
+ lexicons.set(key, lexicon);
+ }
+ return lexicon;
+}
+
+interface SampledMonth {
+ readonly code: string;
+ readonly ordinal: number;
+ readonly mid: PlainDate;
+ readonly monthsInYear: number;
+}
+
+/** Months to learn names from: a few calendar years, so leap months appear. */
+function sampleMonths(calendar: CalendarSystem): SampledMonth[] {
+ if (isGregorianAligned(calendar)) {
+ return Array.from({length: 12}, (_, i) => ({
+ code: `M${String(i + 1).padStart(2, '0')}`,
+ ordinal: i + 1,
+ mid: {year: 2026, month: i + 1, day: 15},
+ monthsInYear: 12,
+ }));
+ }
+ const reference = calendarYearOf(calendar, {year: 2026, month: 6, day: 15});
+ const sampled: SampledMonth[] = [];
+ for (let year = reference - 1; year <= reference + 3; year++) {
+ const starts: {code: string; start: PlainDate}[] = [];
+ for (let n = 1; n <= 13; n++) {
+ for (const leap of ['', 'L']) {
+ const code = `M${String(n).padStart(2, '0')}${leap}`;
+ const start = calendarDateFromFields(calendar, {
+ year,
+ monthCode: code,
+ day: 1,
+ });
+ if (start != null) {
+ starts.push({code, start});
+ }
+ }
+ }
+ starts.sort((a, b) => plainDateDiffDays(b.start, a.start));
+ starts.forEach(({code, start}, i) => {
+ const month = calendarMonthOf(calendar, start);
+ sampled.push({
+ code,
+ ordinal: i + 1,
+ mid: plainDateAddDays(month.start, Math.floor(month.length / 2)),
+ monthsInYear: starts.length,
+ });
+ });
+ }
+ return sampled;
+}
+
+/** The calendar's year number of a Gregorian date, read from Intl. */
+function calendarYearOf(calendar: CalendarSystem, pd: PlainDate): number {
+ const parts = partsOf('en', calendar, YEAR_ONLY, pd);
+ const year = parts.find(
+ p => partType(p) === 'relatedYear' || p.type === 'year',
+ );
+ return Number(normalizeDateText(year?.value ?? '', 'en'));
+}
+
+function fieldOrder(parts: Intl.DateTimeFormatPart[]): DateField[] {
+ const order: DateField[] = [];
+ for (const part of parts) {
+ const type = partType(part) === 'relatedYear' ? 'year' : part.type;
+ if (
+ (type === 'year' || type === 'month' || type === 'day') &&
+ !order.includes(type)
+ ) {
+ order.push(type);
+ }
+ }
+ return order;
+}
+
+function buildLexicon(
+ locale: Locale,
+ calendar: CalendarSystem,
+): CalendarDateLexicon {
+ const locales: Locale[] = locale === 'en' ? ['en'] : [locale, 'en'];
+ const norm = (text: string) => normalizeDateText(text, locale).trim();
+ const months = new Map<string, Set<string>>();
+ const templates = new Map<string, MonthTemplate>();
+ const leapMarkers = new Set<string>();
+ const eras = new Map<string, string>();
+ const yearAliases = new Map<string, string>();
+ const skip = new Set<string>();
+ const trailers = new Set<string>();
+ const weekdays = new Set<string>();
+
+ const addSkip = (text: string, words = skip) => {
+ for (const word of norm(text).replace(NOT_WORDS, ' ').split(/\s+/)) {
+ if (word) {
+ words.add(word);
+ }
+ }
+ };
+ const addMonth = (text: string, {code, ordinal}: SampledMonth) => {
+ const name = norm(text);
+ // A month number with affixes: "11月", "9:e mån", "윤6", "6bis". A name
+ // can also hold another number: Hungarian "Réb. 1" is the third month.
+ const match = /^(\D*)(\d+)(\D*)$/.exec(name);
+ const isOwnNumber = [ordinal, Number(code.slice(1, 3))].includes(
+ Number(match?.[2]),
+ );
+ if (!name || (/\d/.test(name) && (!LETTER.test(name) || isOwnNumber))) {
+ if (match != null && (match[1] || match[3])) {
+ templates.set(`${match[1]}#${match[3]}`, {
+ pre: match[1],
+ post: match[3],
+ isLeap: code.endsWith('L'),
+ });
+ }
+ return;
+ }
+ let codes = months.get(name);
+ if (codes == null) {
+ codes = new Set();
+ months.set(name, codes);
+ }
+ codes.add(code);
+ };
+
+ const sampled = sampleMonths(calendar);
+ const monthWidths: Intl.DateTimeFormatOptions[] = [
+ LONG,
+ {year: 'numeric', month: 'short', day: 'numeric'},
+ NUMERIC,
+ {month: 'long'},
+ {month: 'short'},
+ ];
+ const baseText = new Map<string, string>();
+ for (const month of sampled) {
+ for (const loc of locales) {
+ monthWidths.forEach((options, width) => {
+ const text = partsOf(loc, calendar, options, month.mid).find(
+ p => p.type === 'month',
+ )?.value;
+ if (text == null) {
+ return;
+ }
+ const baseKey = `${loc}|${width}|${month.code.slice(0, 3)}`;
+ if (month.code.endsWith('L')) {
+ // A leap month written as its common month plus a marker ("闰六月").
+ const base = baseText.get(baseKey);
+ if (base != null && text.includes(base) && !/\d/.test(base)) {
+ const marker = norm(text.replace(base, ''));
+ if (marker) {
+ leapMarkers.add(marker);
+ return;
+ }
+ }
+ } else {
+ baseText.set(baseKey, text);
+ }
+ addMonth(text, month);
+ });
+ }
+ }
+
+ const literalFormats: Intl.DateTimeFormatOptions[] = [];
+ for (const options of [
+ NUMERIC,
+ LONG,
+ SHARED_DATE_FORMAT_OPTIONS.date,
+ SHARED_DATE_FORMAT_OPTIONS.date_weekday,
+ LONG_WITH_WEEKDAY,
+ ]) {
+ literalFormats.push(options, displayOptions(locale, calendar, options));
+ }
+ const literalDates = sampled.slice(0, 14).map(m => m.mid);
+ for (const loc of locales) {
+ for (const options of literalFormats) {
+ for (const pd of literalDates) {
+ const parts = partsOf(loc, calendar, options, pd);
+ for (const part of parts) {
+ if (part.type === 'literal' || partType(part) === 'yearName') {
+ addSkip(part.value);
+ }
+ }
+ if (loc === locale) {
+ const tail = parts.at(-1);
+ if (tail?.type === 'literal') {
+ const trailer = norm(tail.value).replace(/\s+/g, '');
+ if (ONLY_SEPARATORS.test(trailer)) {
+ trailers.add(trailer);
+ }
+ }
+ }
+ }
+ }
+ for (let day = 0; day < 7; day++) {
+ const pd = {year: 2026, month: 11, day: 1 + day};
+ for (const options of WEEKDAY_FORMATS) {
+ const text = partsOf(loc, calendar, options, pd).find(
+ p => p.type === 'weekday',
+ )?.value;
+ if (text != null) {
+ addSkip(text);
+ addSkip(text, weekdays);
+ // Vietnamese writes a weekday as a word and a number: "Thứ 2".
+ if (/\d/.test(norm(text))) {
+ skip.add(norm(text));
+ }
+ }
+ }
+ }
+ }
+ if (LUNISOLAR.has(calendar)) {
+ // Year names cycle every 60 years.
+ for (let year = 1996; year < 2057; year++) {
+ for (const loc of locales) {
+ for (const part of partsOf(loc, calendar, LONG, {
+ year,
+ month: 6,
+ day: 15,
+ })) {
+ if (partType(part) === 'yearName') {
+ addSkip(part.value);
+ }
+ }
+ }
+ }
+ }
+
+ const eraArithmetic = new Map<string, EraArithmetic>();
+ const eraWidths: ReadonlyArray<'long' | 'short' | 'narrow'> =
+ calendar === 'japanese' ? ['long', 'short', 'narrow'] : ['long', 'short'];
+ for (const [code, iso] of Object.entries(ERA_SAMPLES[calendar] ?? {})) {
+ const sample = isoToPlainDate(iso);
+ for (const loc of locales) {
+ // A full date can spell the era differently, such as French "EB".
+ for (const options of [
+ ...eraWidths.map(width => ERA_WIDTHS[width]),
+ ...literalFormats,
+ ]) {
+ const text = partsOf(loc, calendar, options, sample).find(
+ p => p.type === 'era',
+ )?.value;
+ if (text != null && norm(text)) {
+ eras.set(norm(text), code);
+ }
+ }
+ }
+ const eraYear = (pd: PlainDate) => calendarEraYear('en', calendar, pd).year;
+ const year = eraYear(sample);
+ const isForward = eraYear({...sample, year: sample.year + 1}) > year;
+ const base = isForward ? sample.year - year : sample.year + year;
+ eraArithmetic.set(code, {base, isForward});
+ const firstYear = {
+ year: isForward ? base + 1 : base - 1,
+ month: 12,
+ day: 31,
+ };
+ // Some locales write era year 1 as a word, such as Japanese 元.
+ if (isGregorianAligned(calendar) && firstYear.year > 0) {
+ const text = partsOf(locale, calendar, LONG_WITH_ERA, firstYear).find(
+ p => p.type === 'year',
+ )?.value;
+ if (text != null && !/\d/.test(norm(text))) {
+ yearAliases.set(norm(text), '1');
+ }
+ }
+ }
+ if (calendar === 'japanese') {
+ eraArithmetic.set('ce', {base: 0, isForward: true});
+ }
+ for (const marker of leapMarkers) {
+ skip.delete(marker);
+ }
+ for (const word of [
+ ...months.keys(),
+ ...eras.keys(),
+ ...yearAliases.keys(),
+ ]) {
+ skip.delete(word);
+ }
+
+ // Whether a typed month number is the month's position in its year (Hebrew)
+ // or its code number (Chinese). Probed with a locale that writes numbers.
+ let isNumericMonthOrdinal = false;
+ const shifted = sampled.find(m => m.ordinal !== Number(m.code.slice(1, 3)));
+ if (shifted != null) {
+ const text = partsOf('sv', calendar, NUMERIC, shifted.mid).find(
+ p => p.type === 'month',
+ )?.value;
+ isNumericMonthOrdinal =
+ Number(normalizeDateText(text ?? '', 'sv').replace(/\D+/g, '')) ===
+ shifted.ordinal;
+ }
+
+ const vocabularySet = new Set([
+ ...months.keys(),
+ ...eras.keys(),
+ ...skip,
+ ...leapMarkers,
+ ...yearAliases.keys(),
+ ]);
+ const sample = {year: 2026, month: 11, day: 2};
+ return {
+ locale,
+ calendar,
+ order: fieldOrder(partsOf(locale, calendar, NUMERIC, sample)),
+ nameOrder: fieldOrder(partsOf(locale, calendar, LONG, sample)),
+ months,
+ monthTemplates: [...templates.values()].sort(
+ (a, b) => b.pre.length + b.post.length - (a.pre.length + a.post.length),
+ ),
+ leapMarkers,
+ eras,
+ yearAliases,
+ trailers,
+ weekdays,
+ vocabulary: [...vocabularySet].sort((a, b) => b.length - a.length),
+ vocabularySet,
+ isNumericMonthOrdinal,
+ eraArithmetic,
+ };
+}
+
+/** The era name and era year Intl writes for a date. */
+function calendarEraYear(
+ locale: Locale,
+ calendar: CalendarSystem,
+ pd: PlainDate,
+): {era: string; year: number} {
+ const parts = partsOf(locale, calendar, ERA_AND_YEAR, pd);
+ return {
+ era: parts.find(p => p.type === 'era')?.value ?? '',
+ year: Number(
+ normalizeDateText(
+ parts.find(p => p.type === 'year' || partType(p) === 'relatedYear')
+ ?.value ?? '',
+ locale,
+ ),
+ ),
+ };
+}
+
+// =============================================================================
+// Tokens
+// =============================================================================
+
+type Token =
+ | {readonly t: 'num'; readonly v: string; readonly isAlias?: boolean}
+ | {
+ readonly t: 'month';
+ readonly codes: ReadonlySet<string>;
+ readonly isWeekday?: boolean;
+ }
+ | {readonly t: 'monthNum'; readonly v: string; readonly isLeap: boolean}
+ | {readonly t: 'era'; readonly code: string; readonly isWeekday?: boolean}
+ | {readonly t: 'leap'}
+ | {readonly t: 'word'}
+ | {readonly t: 'sep'; readonly v: string};
+
+type Tokens = Token[] | 'incomplete' | 'unreadable';
+
+function tokenize(s: string, lex: CalendarDateLexicon): Tokens {
+ const out: Token[] = [];
+ let i = 0;
+ const end = s.trimEnd().length;
+ while (i < end) {
+ const ch = s[i];
+ if (/\s/.test(ch)) {
+ i++;
+ continue;
+ }
+ const template = matchTemplate(s, i, lex);
+ if (template != null) {
+ out.push(template.token);
+ i = template.end;
+ continue;
+ }
+ if (/\d/.test(ch)) {
+ let j = i;
+ while (j < s.length && /\d/.test(s[j])) {
+ j++;
+ }
+ out.push({t: 'num', v: s.slice(i, j)});
+ i = j;
+ continue;
+ }
+ const word = matchWord(s, i, lex);
+ if (word != null) {
+ out.push(wordToken(word, lex));
+ i += word.length;
+ continue;
+ }
+ if (SEPARATOR.test(ch)) {
+ let j = i;
+ while (j < end && (SEPARATOR.test(s[j]) || /\s/.test(s[j]))) {
+ j++;
+ }
+ out.push({t: 'sep', v: s.slice(i, j).replace(/\s+/g, '')});
+ i = j;
+ continue;
+ }
+ let j = i;
+ while (j < end && LETTER.test(s[j])) {
+ j++;
+ }
+ const run = s.slice(i, j);
+ const joined = matchJoinedWord(s, i, lex);
+ if (joined != null) {
+ out.push(wordToken(joined, lex));
+ i += joined.length;
+ continue;
+ }
+ const monthCodes = monthByPrefix(run, lex);
+ if (monthCodes != null) {
+ out.push({t: 'month', codes: monthCodes});
+ i = j;
+ continue;
+ }
+ if (j >= end && run && lex.vocabulary.some(w => w.startsWith(run))) {
+ return 'incomplete';
+ }
+ return 'unreadable';
+ }
+ return out;
+}
+
+function matchTemplate(
+ s: string,
+ i: number,
+ lex: CalendarDateLexicon,
+): {token: Token; end: number} | null {
+ for (const template of lex.monthTemplates) {
+ if (!s.startsWith(template.pre, i)) {
+ continue;
+ }
+ const digits = /^\d+/.exec(s.slice(i + template.pre.length));
+ if (digits == null) {
+ continue;
+ }
+ const after = i + template.pre.length + digits[0].length;
+ if (template.post && !s.startsWith(template.post, after)) {
+ continue;
+ }
+ if (!template.post && !template.pre) {
+ continue;
+ }
+ return {
+ token: {t: 'monthNum', v: digits[0], isLeap: template.isLeap},
+ end: after + template.post.length,
+ };
+ }
+ return null;
+}
+
+/** The longest known word at `i` that ends where a word may end. */
+function matchWord(
+ s: string,
+ i: number,
+ lex: CalendarDateLexicon,
+): string | null {
+ for (const word of lex.vocabulary) {
+ if (!s.startsWith(word, i)) {
+ continue;
+ }
+ const next = s[i + word.length] ?? '';
+ const last = word[word.length - 1];
+ if (
+ !LETTER.test(next) ||
+ SPACELESS.test(next) ||
+ SPACELESS.test(last) ||
+ !LETTER.test(last)
+ ) {
+ return word;
+ }
+ }
+ return null;
+}
+
+/**
+ * A known word joined to the next one with no space, such as Hebrew ב before
+ * a month name or a leap marker after it ("Eighth Monthbis").
+ */
+function matchJoinedWord(
+ s: string,
+ i: number,
+ lex: CalendarDateLexicon,
+): string | null {
+ for (const word of lex.vocabulary) {
+ if (!s.startsWith(word, i)) {
+ continue;
+ }
+ const next = i + word.length;
+ if (lex.vocabulary.some(w => s.startsWith(w, next))) {
+ return word;
+ }
+ }
+ return null;
+}
+
+function wordToken(word: string, lex: CalendarDateLexicon): Token {
+ const isWeekday = lex.weekdays.has(word.replace(NOT_WORDS, ''));
+ const codes = lex.months.get(word);
+ if (codes != null) {
+ return {t: 'month', codes, isWeekday};
+ }
+ const era = lex.eras.get(word);
+ if (era != null) {
+ return {t: 'era', code: era, isWeekday};
+ }
+ if (lex.leapMarkers.has(word)) {
+ return {t: 'leap'};
+ }
+ const alias = lex.yearAliases.get(word);
+ if (alias != null) {
+ return {t: 'num', v: alias, isAlias: true};
+ }
+ return {t: 'word'};
+}
+
+/** The month a typed abbreviation names when it starts only one month name. */
+function monthByPrefix(
+ run: string,
+ lex: CalendarDateLexicon,
+): ReadonlySet<string> | null {
+ if (run.length < 3) {
+ return null;
+ }
+ let found: ReadonlySet<string> | null = null;
+ for (const [name, codes] of lex.months) {
+ if (name.startsWith(run)) {
+ if (found != null && !sameCodes(found, codes)) {
+ return null;
+ }
+ found = codes;
+ }
+ }
+ return found;
+}
+
+/**
+ * A weekday word can also be a month or era name, such as French "mar.". When
+ * the text has another month or era, the first such word is the weekday.
+ */
+function weekdaysAsWords(tokens: Token[]): Token[] {
+ let out = tokens;
+ for (const kinds of [['month', 'monthNum'], ['era']]) {
+ const named = out.filter(t => kinds.includes(t.t));
+ const weekday = named.find(t => 'isWeekday' in t && t.isWeekday);
+ if (named.length > 1 && weekday != null) {
+ out = out.map(t => (t === weekday ? {t: 'word'} : t));
+ }
+ }
+ return out;
+}
+
+function sameCodes(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
+ return a.size === b.size && [...a].every(code => b.has(code));
+}
+
+// =============================================================================
+// Parsing
+// =============================================================================
+
+const INCOMPLETE: CalendarDateParseResult = {kind: 'incomplete'};
+const UNREADABLE: CalendarDateParseResult = {kind: 'unreadable'};
+const EMPTY: CalendarDateParseResult = {kind: 'empty'};
+
+type DateFields = {
+ -readonly [K in keyof CalendarDateFields]: CalendarDateFields[K];
+};
+
+/**
+ * Reads typed text as a date in the lexicon's calendar. Values are Gregorian.
+ * The result tells an empty field, part of a date, unreadable text, a date the
+ * calendar does not have, a date out of range, and a date apart.
+ */
+export function parseCalendarDate(
+ text: string,
+ lex: CalendarDateLexicon,
+ options: CalendarDateParseOptions = {},
+): CalendarDateParseResult {
+ const s = normalizeDateText(text, lex.locale).trim();
+ if (!s) {
+ return EMPTY;
+ }
+ const {isDateDisabled, isoIsGregorian = false} = options;
+ if (isoIsGregorian) {
+ const iso = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(s);
+ if (iso != null) {
+ return finish(
+ gregorianDate(+iso[1], +iso[2], +iso[3]),
+ true,
+ isDateDisabled,
+ );
+ }
+ }
+ const read = tokenize(s, lex);
+ if (read === 'incomplete' || read === 'unreadable') {
+ return read === 'incomplete' ? INCOMPLETE : UNREADABLE;
+ }
+ const tokens = weekdaysAsWords(read);
+ const nums = tokens.filter(
+ (token): token is Extract<Token, {t: 'num'}> => token.t === 'num',
+ );
+ const monthTokens = tokens.filter(
+ token => token.t === 'month' || token.t === 'monthNum',
+ );
+ const eraCodes = new Set(
+ tokens.flatMap(token => (token.t === 'era' ? [token.code] : [])),
+ );
+ const isLeap = tokens.some(
+ token => token.t === 'leap' || (token.t === 'monthNum' && token.isLeap),
+ );
+ if (monthTokens.length > 1 || eraCodes.size > 1) {
+ return UNREADABLE;
+ }
+ if (nums.length === 0 && monthTokens.length === 0) {
+ return eraCodes.size > 0 ? INCOMPLETE : UNREADABLE;
+ }
+ const typedEra = eraCodes.size === 1 ? [...eraCodes][0] : undefined;
+
+ const assigned = new Map<Token, DateField>();
+ let monthCode: string | undefined;
+ let monthOrdinal: number | undefined;
+ const monthToken = monthTokens[0];
+ if (monthToken != null) {
+ if (monthToken.t === 'month') {
+ if (monthToken.codes.size !== 1) {
+ return UNREADABLE;
+ }
+ monthCode = [...monthToken.codes][0];
+ } else if (lex.isNumericMonthOrdinal) {
+ monthOrdinal = Number(monthToken.v);
+ } else {
+ monthCode = `M${monthToken.v.padStart(2, '0')}`;
+ }
+ if (nums.length === 0 || nums.length > 2) {
+ return nums.length === 0 ? INCOMPLETE : UNREADABLE;
+ }
+ let rest = lex.nameOrder.filter(field => field !== 'month');
+ const long = nums.filter(n => n.v.length >= 3 && !n.isAlias);
+ if (nums.length === 1) {
+ rest = long.length === 1 ? ['year'] : ['day'];
+ } else if (long.length === 1) {
+ // With a month name, a number of three or more digits is the year.
+ rest = nums[0] === long[0] ? ['year', 'day'] : ['day', 'year'];
+ }
+ nums.forEach((n, k) => assigned.set(n, rest[k]));
+ } else {
+ if (nums.length < 2) {
+ return INCOMPLETE;
+ }
+ if (nums.length > 3 || !sameSeparators(tokens)) {
+ return UNREADABLE;
+ }
+ let order: ReadonlyArray<DateField> =
+ nums.length === 2
+ ? lex.order.filter(field => field !== 'year')
+ : lex.order;
+ if (nums.length === 3 && order[0] !== 'year' && nums[0].v.length >= 3) {
+ // ISO-shaped text: a leading long number is the year.
+ order = ['year', 'month', 'day'];
+ }
+ if (nums.length === 2 && nums.some(n => n.v.length >= 3)) {
+ return INCOMPLETE;
+ }
+ nums.forEach((n, k) => assigned.set(n, order[k]));
+ }
+ const tokenOf = (field: DateField) =>
+ nums.find(n => assigned.get(n) === field);
+ const dayToken = tokenOf('day');
+ const yearToken = tokenOf('year');
+ const monthNumToken = tokenOf('month');
+ if (dayToken == null) {
+ return INCOMPLETE;
+ }
+ if (monthNumToken != null) {
+ if (lex.isNumericMonthOrdinal) {
+ monthOrdinal = Number(monthNumToken.v);
+ } else {
+ monthCode = `M${String(Number(monthNumToken.v)).padStart(2, '0')}`;
+ }
+ }
+ if (monthCode != null && isLeap && !monthCode.endsWith('L')) {
+ monthCode += 'L';
+ }
+ const day = Number(dayToken.v);
+ const monthNumber = monthOrdinal ?? Number(monthCode?.slice(1, 3) ?? 0);
+ if (day < 1 || day > 31 || monthNumber < 1 || monthNumber > 13) {
+ // A lone 0 starts a two-digit day or month such as 07.
+ const startsField = [dayToken, monthNumToken].some(t => t?.v === '0');
+ return startsField ? INCOMPLETE : UNREADABLE;
+ }
+
+ const today = options.today ?? plainDateToday();
+ const dateFields: DateFields = {day};
+ if (monthCode != null) {
+ dateFields.monthCode = monthCode;
+ } else {
+ dateFields.month = monthOrdinal;
+ }
+ let isYearComplete = false;
+ if (yearToken == null) {
+ applyDefaultYear(dateFields, lex, today);
+ } else {
+ const digits = yearToken.isAlias ? 1 : yearToken.v.length;
+ const year = Number(yearToken.v);
+ const isYearLast = lastNumber(tokens) === yearToken;
+ const {calendar} = lex;
+ if (typedEra != null) {
+ dateFields.era = typedEra;
+ dateFields.eraYear = year;
+ isYearComplete = true;
+ } else if (calendar === 'japanese' && digits <= 2) {
+ const era = currentEra(lex, today);
+ if (era == null) {
+ return UNREADABLE;
+ }
+ dateFields.era = era;
+ dateFields.eraYear = year;
+ isYearComplete = !isYearLast;
+ } else if (calendar === 'japanese' && digits === 4) {
+ dateFields.era = 'ce';
+ dateFields.eraYear = year;
+ isYearComplete = true;
+ } else if (calendar === 'roc') {
+ dateFields.era = 'roc';
+ dateFields.eraYear = year;
+ isYearComplete = digits >= 4 || !isYearLast;
+ } else if (digits === 2) {
+ dateFields.year = windowedYear(year, calendarYearOf(calendar, today));
+ } else if (digits >= 4) {
+ dateFields.year = year;
+ isYearComplete = true;
+ } else {
+ return INCOMPLETE;
+ }
+ }
+
+ const date = resolveDate(lex, dateFields);
+ const isComplete =
+ yearToken != null &&
+ isYearComplete &&
+ isLastFieldClosed(tokens, lex, assigned, date);
+ return finish(date, isComplete, isDateDisabled);
+}
+
+function finish(
+ date: PlainDate | null,
+ isComplete: boolean,
+ isDateDisabled: ((date: PlainDate) => boolean) | undefined,
+): CalendarDateParseResult {
+ if (date == null) {
+ return {kind: 'nonexistent', isComplete};
+ }
+ if (isDateDisabled?.(date)) {
+ return {kind: 'outOfRange', date, isComplete};
+ }
+ return {kind: 'value', date, isComplete};
+}
+
+function sameSeparators(tokens: Token[]): boolean {
+ let previous: string | null = null;
+ let seenNumber = false;
+ let pending: string | null = null;
+ for (const token of tokens) {
+ if (token.t === 'num') {
+ if (seenNumber) {
+ const separator = pending ?? '';
+ if (previous != null && separator !== previous) {
+ return false;
+ }
+ previous = separator;
+ }
+ seenNumber = true;
+ pending = null;
+ } else if (token.t === 'sep') {
+ pending = token.v;
+ } else {
+ pending = null;
+ seenNumber = false;
+ previous = null;
+ }
+ }
+ return true;
+}
+
+function lastNumber(tokens: Token[]): Token | undefined {
+ const last = tokens.filter(token => token.t !== 'sep').at(-1);
+ return last?.t === 'num' ? last : undefined;
+}
+
+/**
+ * Whether the text has stopped growing: no separator trails it, and its last
+ * field cannot take another digit.
+ */
+function isLastFieldClosed(
+ tokens: Token[],
+ lex: CalendarDateLexicon,
+ assigned: ReadonlyMap<Token, DateField>,
+ date: PlainDate | null,
+): boolean {
+ const last = tokens.at(-1);
+ if (last == null) {
+ return false;
+ }
+ if (last.t === 'sep') {
+ return lex.trailers.has(last.v);
+ }
+ if (last.t !== 'num') {
+ return true;
+ }
+ const field = assigned.get(last);
+ if (field === 'year' || last.v.length >= 2) {
+ return true;
+ }
+ const value = Number(last.v);
+ if (field === 'day') {
+ // Not the month's own length: a 3 can start a 30 that the month lacks,
+ // and the field must then report that day, not the 3rd.
+ return value * 10 > 31;
+ }
+ const monthsInYear =
+ date == null ? 13 : calendarMonthsInYear(lex.calendar, date);
+ return value * 10 > monthsInYear;
+}
+
+/**
+ * Resolves a two-digit year to the century that puts it at most 80 years
+ * before and 19 years after the current year.
+ */
+function windowedYear(twoDigits: number, current: number): number {
+ let year = current - (current % 100) + twoDigits;
+ if (year > current + 19) {
+ year -= 100;
+ } else if (year < current - 80) {
+ year += 100;
+ }
+ return year;
+}
+
+function currentEra(
+ lex: CalendarDateLexicon,
+ today: PlainDate,
+): string | undefined {
+ const {era} = calendarEraYear('en', lex.calendar, today);
+ return lex.eras.get(normalizeDateText(era, lex.locale).trim());
+}
+
+function applyDefaultYear(
+ fields: DateFields,
+ lex: CalendarDateLexicon,
+ today: PlainDate,
+): void {
+ if (lex.eraArithmetic.size > 0 && !WITHOUT_ERA.has(lex.calendar)) {
+ const {era, year} = calendarEraYear('en', lex.calendar, today);
+ const code = lex.eras.get(normalizeDateText(era, lex.locale).trim());
+ if (code != null) {
+ fields.era = code;
+ fields.eraYear = year;
+ return;
+ }
+ }
+ fields.year = calendarYearOf(lex.calendar, today);
+}
+
+function gregorianDate(
+ year: number,
+ month: number,
+ day: number,
+): PlainDate | null {
+ if (
+ year < 1 ||
+ year > 9999 ||
+ month < 1 ||
+ month > 12 ||
+ day < 1 ||
+ day > getDaysInMonth(year, month)
+ ) {
+ return null;
+ }
+ return {year, month, day};
+}
+
+/** The Gregorian date for calendar fields, or null when it does not exist. */
+function resolveDate(
+ lex: CalendarDateLexicon,
+ fields: DateFields,
+): PlainDate | null {
+ const {calendar} = lex;
+ if (!isGregorianAligned(calendar)) {
+ const defined = Object.fromEntries(
+ Object.entries(fields).filter(([, value]) => value !== undefined),
+ ) as DateFields;
+ const date = calendarDateFromFields(calendar, defined);
+ return date != null && date.year >= 1 && date.year <= 9999 ? date : null;
+ }
+ if (fields.monthCode?.endsWith('L')) {
+ return null;
+ }
+ const month = fields.month ?? Number(fields.monthCode?.slice(1, 3));
+ let gregorianYear: number;
+ if (fields.era != null) {
+ const arithmetic = lex.eraArithmetic.get(fields.era);
+ if (arithmetic == null || fields.eraYear == null || fields.eraYear < 1) {
+ return null;
+ }
+ gregorianYear = arithmetic.isForward
+ ? arithmetic.base + fields.eraYear
+ : arithmetic.base - fields.eraYear;
+ } else {
+ const defaultEra = calendar === 'buddhist' ? 'be' : 'ce';
+ const arithmetic = lex.eraArithmetic.get(defaultEra);
+ gregorianYear = (arithmetic?.base ?? 0) + (fields.year ?? 0);
+ }
+ const date = gregorianDate(gregorianYear, month, fields.day);
+ if (date == null || calendar !== 'japanese' || fields.era === 'ce') {
+ return date;
+ }
+ // Each Japanese era ends on a set day; a year past it is not in that era.
+ const written = calendarEraYear('en', calendar, date);
+ const era = lex.eras.get(normalizeDateText(written.era, lex.locale).trim());
+ return era === fields.era && written.year === fields.eraYear ? date : null;
+}
+
+// =============================================================================
+// Display
+// =============================================================================
+
+const displayOptionCache = new WeakMap<
+ Intl.DateTimeFormatOptions,
+ Map<string, Intl.DateTimeFormatOptions>
+>();
+
+/**
+ * Adds the era to a format that omits it, so a year never reads as a
+ * Gregorian year. Keeps the locale's own pattern when the era would reorder
+ * the fields.
+ */
+function displayOptions(
+ locale: Locale,
+ calendar: CalendarSystem,
+ options: Intl.DateTimeFormatOptions,
+): Intl.DateTimeFormatOptions {
+ if (WITHOUT_ERA.has(calendar)) {
+ return options;
+ }
+ let byLocale = displayOptionCache.get(options);
+ if (byLocale == null) {
+ byLocale = new Map();
+ displayOptionCache.set(options, byLocale);
+ }
+ const key = `${locale}|${calendar}`;
+ let result = byLocale.get(key);
+ if (result == null) {
+ const sample = {year: 2026, month: 11, day: 2};
+ const parts = partsOf(locale, calendar, options, sample);
+ result = options;
+ if (!parts.some(p => p.type === 'era')) {
+ const withEra = {...options, era: 'short'} as const;
+ const eraParts = partsOf(locale, calendar, withEra, sample);
+ if (fieldOrder(parts).join() === fieldOrder(eraParts).join()) {
+ result = withEra;
+ }
+ }
+ byLocale.set(key, result);
+ }
+ return result;
+}
+
+function formatInCalendar(
+ pd: PlainDate,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+ calendar: CalendarSystem,
+): string {
+ if (LUNISOLAR.has(calendar)) {
+ return formatCalendarDate(calendar, pd, options, locale, {
+ relatedYear: true,
+ });
+ }
+ return plainDateFormat(
+ pd,
+ {...displayOptions(locale, calendar, options), calendar},
+ locale,
+ );
+}
+
+/**
+ * The committed text of a date field in a calendar. Gregorian text is the
+ * shared Timestamp date text; `system_date` is always the ISO date.
+ */
+export function formatCalendarDateText(
+ pd: PlainDate,
+ format: SharedDateFormat,
+ locale: Locale,
+ calendar: CalendarSystem,
+): string {
+ const resolved = textCalendar(calendar);
+ if (format === 'system_date' || resolved === 'gregory') {
+ return formatSharedDate(pd, format, locale);
+ }
+ return formatInCalendar(
+ pd,
+ SHARED_DATE_FORMAT_OPTIONS[format],
+ locale,
+ resolved,
+ );
+}
+
+/** An example date in the calendar's numeric pattern, with its era. */
+export function formatCalendarDateHint(
+ pd: PlainDate,
+ locale: Locale,
+ calendar: CalendarSystem,
+): string {
+ return formatInCalendar(pd, NUMERIC, locale, textCalendar(calendar));
+}
+
+/** The calendar's name in the locale, such as "Persian Calendar". */
+export function calendarDisplayName(
+ calendar: CalendarSystem,
+ locale: Locale,
+): string {
+ try {
+ return (
+ new Intl.DisplayNames(locale, {type: 'calendar'}).of(calendar) ?? calendar
+ );
+ } catch {
+ return calendar;
+ }
+}
diff --git a/packages/core/src/utils/calendarSystem.ts b/packages/core/src/utils/calendarSystem.ts
index 77d287f644..a688f867a5 100644
--- a/packages/core/src/utils/calendarSystem.ts
+++ b/packages/core/src/utils/calendarSystem.ts
@@ -382,15 +382,20 @@ function monthPartsKey(parts: Intl.DateTimeFormatPart[]): string {
* The label always names the month and day that the grid shows. Intl and the
* runtime's Temporal can disagree on where a month of the Chinese or Dangi
* calendar starts; the label then takes its month and year from the middle of
- * the Temporal month, and its day from Temporal.
+ * the Temporal month, and its day from Temporal. With `relatedYear`, a
+ * Chinese or Dangi year that the locale names only by its place in the 60-year
+ * cycle becomes the related Gregorian year.
*/
export function formatCalendarDate(
calendar: CalendarSystem,
pd: PlainDate,
options: Intl.DateTimeFormatOptions,
locale: Locale,
+ labelOptions?: {readonly relatedYear?: boolean},
): string {
- return joinParts(formatCalendarDateToParts(calendar, pd, options, locale));
+ return joinParts(
+ formatCalendarDateToParts(calendar, pd, options, locale, labelOptions),
+ );
}
/** The parts of `formatCalendarDate`'s label. */
@@ -399,9 +404,39 @@ export function formatCalendarDateToParts(
pd: PlainDate,
options: Intl.DateTimeFormatOptions,
locale: Locale,
+ {relatedYear = false}: {readonly relatedYear?: boolean} = {},
): Intl.DateTimeFormatPart[] {
const parts = formatToParts(labelCalendar(calendar), pd, options, locale);
- return withTemporalDay(calendar, pd, parts, options, locale);
+ const fixed = withTemporalDay(calendar, pd, parts, options, locale);
+ return relatedYear
+ ? withRelatedYear(calendar, pd, fixed, options, locale)
+ : fixed;
+}
+
+function withRelatedYear(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ parts: Intl.DateTimeFormatPart[],
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+): Intl.DateTimeFormatPart[] {
+ if (
+ (calendar !== 'chinese' && calendar !== 'dangi') ||
+ !isCalendarSystemAvailable(calendar) ||
+ parts.some(part => (part.type as string) === 'relatedYear')
+ ) {
+ return parts;
+ }
+ const {numberingSystem} = dateTimeFormatFor(locale, {
+ ...options,
+ calendar,
+ timeZone: 'UTC',
+ }).resolvedOptions();
+ const {year} = inCalendar(calendar, pd);
+ const value = plainDateFormatDayNumber(year, locale, numberingSystem);
+ return parts.map(part =>
+ /^year(Name)?$/.test(part.type) ? {...part, value} : part,
+ );
}
// Returns `parts` itself where Intl already names Temporal's month and day.
diff --git a/packages/core/src/utils/plainDate.test.ts b/packages/core/src/utils/plainDate.test.ts
index af6f5ca942..1588a441c9 100644
--- a/packages/core/src/utils/plainDate.test.ts
+++ b/packages/core/src/utils/plainDate.test.ts
@@ -38,6 +38,7 @@ import {
DATE_FORMAT_MONTH_YEAR,
plainDateWeekFieldName,
plainDateFormatToParts,
+ nearestAcceptedDate,
} from './plainDate';
import type {ISODateString} from './dateTypes';
@@ -1087,3 +1088,69 @@ describe('plainDateWeekdayNames', () => {
expect(plainDateWeekdayNames('xx-ZZ')).toBeNull();
});
});
+
+describe('nearestAcceptedDate', () => {
+ const d = plainDateFromISO;
+ const isWeekend = (pd: PlainDate) =>
+ plainDateDayOfWeek(pd) === 0 || plainDateDayOfWeek(pd) === 6;
+
+ it('returns the target inside the bounds', () => {
+ expect(
+ nearestAcceptedDate(d('2026-11-04'), {
+ min: d('2026-01-01'),
+ max: d('2026-12-31'),
+ }),
+ ).toEqual(d('2026-11-04'));
+ });
+
+ it('clamps a target before min to min', () => {
+ expect(
+ nearestAcceptedDate(d('2026-11-04'), {min: d('2027-03-01')}),
+ ).toEqual(d('2027-03-01'));
+ });
+
+ it('clamps a target after max to max', () => {
+ expect(
+ nearestAcceptedDate(d('2026-11-04'), {max: d('2025-06-30')}),
+ ).toEqual(d('2025-06-30'));
+ });
+
+ it('moves a disabled target to the nearest enabled day', () => {
+ // 2026-11-07 is a Saturday: Friday is one day away, Monday two.
+ expect(
+ nearestAcceptedDate(d('2026-11-07'), {isDateDisabled: isWeekend}),
+ ).toEqual(d('2026-11-06'));
+ // 2026-11-08 is a Sunday: Monday is one day away, Friday two.
+ expect(
+ nearestAcceptedDate(d('2026-11-08'), {isDateDisabled: isWeekend}),
+ ).toEqual(d('2026-11-09'));
+ });
+
+ it('prefers the later day on a tie', () => {
+ expect(
+ nearestAcceptedDate(d('2026-11-04'), {
+ isDateDisabled: pd => plainDateIsEqual(pd, d('2026-11-04')),
+ }),
+ ).toEqual(d('2026-11-05'));
+ });
+
+ it('searches only inside the bounds', () => {
+ // max is a Saturday; the Sunday after it is outside the bounds.
+ expect(
+ nearestAcceptedDate(d('2026-12-01'), {
+ max: d('2026-11-07'),
+ isDateDisabled: pd => isWeekend(pd) || plainDateDayOfWeek(pd) === 5,
+ }),
+ ).toEqual(d('2026-11-05'));
+ });
+
+ it('returns the clamped date when every day in the window is disabled', () => {
+ expect(
+ nearestAcceptedDate(d('2026-11-04'), {
+ min: d('2026-11-10'),
+ isDateDisabled: () => true,
+ searchDays: 30,
+ }),
+ ).toEqual(d('2026-11-10'));
+ });
+});
diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.ts
index 5af6ee6e08..e996ec6e6a 100644
--- a/packages/core/src/utils/plainDate.ts
+++ b/packages/core/src/utils/plainDate.ts
@@ -300,6 +300,52 @@ export function plainDateIsInRange(
return compare(pd, range[0]) >= 0 && compare(pd, range[1]) <= 0;
}
+export interface NearestAcceptedDateOptions {
+ min?: PlainDate | null;
+ max?: PlainDate | null;
+ /** Rejects a date inside the bounds, such as a date constraint. */
+ isDateDisabled?: (date: PlainDate) => boolean;
+ /** How many days to search on each side of the clamped date. */
+ searchDays?: number;
+}
+
+/**
+ * The date nearest to `target` that a field accepts. It clamps `target` into
+ * [`min`, `max`], then searches outward one day at a time, inside the bounds,
+ * for a date that `isDateDisabled` allows. On a tie the later date wins. When
+ * no date inside the search window is allowed, it returns the clamped date.
+ */
+export function nearestAcceptedDate(
+ target: PlainDate,
+ {min, max, isDateDisabled, searchDays = 366}: NearestAcceptedDateOptions,
+): PlainDate {
+ let clamped = target;
+ if (min != null && compare(clamped, min) < 0) {
+ clamped = min;
+ }
+ if (max != null && compare(clamped, max) > 0) {
+ clamped = max;
+ }
+ if (isDateDisabled == null || !isDateDisabled(clamped)) {
+ return clamped;
+ }
+ const isAccepted = (date: PlainDate) =>
+ (min == null || compare(date, min) >= 0) &&
+ (max == null || compare(date, max) <= 0) &&
+ !isDateDisabled(date);
+ for (let offset = 1; offset <= searchDays; offset += 1) {
+ const later = plainDateAddDays(clamped, offset);
+ if (isAccepted(later)) {
+ return later;
+ }
+ const earlier = plainDateAddDays(clamped, -offset);
+ if (isAccepted(earlier)) {
+ return earlier;
+ }
+ }
+ return clamped;
+}
+
export function plainDateSetFirstOfMonth(pd: PlainDate): PlainDate {
return {year: pd.year, month: pd.month, day: 1};
}