Skip to content

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

TypeScript

feat(Timestamp, PowerSearch): write dates in the provider's calendar (#9639)

nynexman4464edf7128e3645
diff --git a/.changeset/calendar-systems-formatters.md b/.changeset/calendar-systems-formatters.md
new file mode 100644
index 0000000000..fabe047532
--- /dev/null
+++ b/.changeset/calendar-systems-formatters.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Built-in date formats follow the calendar of the `InternationalizationProvider`. With `calendar="persian"`, Timestamp's `date`, `date_long`, `date_weekday`, and `date_time` formats, the full date in its hover card and accessible name, and PowerSearch date values are written in that calendar, the same one `Calendar` shows. A provider locale with a `-u-ca-` keyword keeps Gregorian dates; set `calendar` to choose one. `date_time` keeps its time of day. The editor a PowerSearch date value opens still shows Gregorian dates. `time`, the relative formats, `system_*`, and `unix_seconds` do not change, and without a provider calendar every output stays the same. `formatSharedDate` from `@astryxdesign/core/utils` and `formatFilterValue` from `@astryxdesign/core/PowerSearch/utils` take an optional trailing `calendar` argument that defaults to `'gregory'`. Each of these dates names the month and day that `Calendar` shows for the same day, as does `plainDateFormat` with a `calendar` option other than `'gregory'`. A calendar that needs `Temporal` shows Gregorian dates where the runtime lacks it, as the date components do.
+
+@nynexman4464
diff --git a/apps/storybook/stories/CalendarSystems.stories.tsx b/apps/storybook/stories/CalendarSystems.stories.tsx
index 80901840aa..34c896da13 100644
--- a/apps/storybook/stories/CalendarSystems.stories.tsx
+++ b/apps/storybook/stories/CalendarSystems.stories.tsx
@@ -2,8 +2,10 @@
/**
* @file CalendarSystems.stories.tsx
- * @input InternationalizationProvider locale and calendar, Calendar
- * @output Calendar in each kind of calendar system, with its Gregorian value
+ * @input InternationalizationProvider locale and calendar, Calendar,
+ * Timestamp, PowerSearch
+ * @output Calendar in each kind of calendar system, with its Gregorian value,
+ * and the built-in date formatters in the provider's calendar
* @position Storybook verification stories for calendar systems; excluded from
* the visual matrix because the months depend on the runtime's Temporal
*/
@@ -19,6 +21,12 @@ import {
type Locale,
} from '@astryxdesign/core/i18n';
import {Heading, Text} from '@astryxdesign/core/Text';
+import {Timestamp} from '@astryxdesign/core/Timestamp';
+import {
+ PowerSearch,
+ type PowerSearchConfig,
+ type PowerSearchFilter,
+} from '@astryxdesign/core/PowerSearch';
import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
const meta = {
@@ -211,6 +219,108 @@ export const Iso8601 = story(
'The ISO 8601 calendar has Gregorian months and uses Gregorian month names.',
);
+const formatterConfig: PowerSearchConfig = {
+ name: 'Dates',
+ fields: [
+ {
+ key: 'created',
+ label: 'Created',
+ defaultOperator: 'after',
+ operators: [
+ {key: 'after', label: 'after', value: {type: 'date_absolute'}},
+ ],
+ },
+ ],
+};
+
+const formatterFilters: PowerSearchFilter[] = [
+ {
+ field: 'created',
+ operator: 'after',
+ value: {
+ type: 'date_absolute',
+ unixSeconds: Date.parse('2026-10-30T12:00:00Z') / 1000,
+ },
+ },
+];
+
+const FORMATTED_INSTANT = '2026-10-30T12:00:00Z';
+
+function FormattedDatesView({
+ title,
+ locale,
+ calendar,
+}: {
+ title: string;
+ locale: Locale;
+ calendar?: CalendarSystem;
+}) {
+ return (
+ <InternationalizationProvider locale={locale} calendar={calendar}>
+ <section
+ aria-label={title}
+ dir={getLocaleDirection(locale)}
+ {...stylex.props(styles.panel)}>
+ <Heading level={2}>{title}</Heading>
+ {(['date', 'date_long', 'date_weekday', 'date_time'] as const).map(
+ format => (
+ <Text key={format}>
+ <code>{format}</code>:{' '}
+ <Timestamp
+ value={FORMATTED_INSTANT}
+ format={format}
+ data-testid={`timestamp-${format}`}
+ />
+ </Text>
+ ),
+ )}
+ <Text>
+ <code>system_date_time</code>:{' '}
+ <Timestamp
+ value={FORMATTED_INSTANT}
+ format="system_date_time"
+ data-testid="timestamp-system_date_time"
+ />
+ </Text>
+ <div {...stylex.props(styles.search)}>
+ <PowerSearch
+ config={formatterConfig}
+ filters={formatterFilters}
+ onChange={() => {}}
+ timezoneID="UTC"
+ />
+ </div>
+ <Calendar value="2026-10-30" />
+ </section>
+ </InternationalizationProvider>
+ );
+}
+
+export const FormattedDatesPersian: Story = {
+ render: () => (
+ <div {...stylex.props(styles.row)}>
+ <FormattedDatesView
+ title="Persian calendar, English"
+ locale="en"
+ calendar="persian"
+ />
+ <FormattedDatesView
+ title="Persian, fa-IR"
+ locale="fa-IR"
+ calendar="persian"
+ />
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ "Timestamp's date formats, a PowerSearch date value, and Calendar follow the provider's calendar. `system_date_time` stays Gregorian ISO.",
+ },
+ },
+ },
+};
+
const styles = stylex.create({
panel: {
display: 'flex',
@@ -218,4 +328,13 @@ const styles = stylex.create({
gap: spacingVars['--spacing-4'],
alignItems: 'flex-start',
},
+ row: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: spacingVars['--spacing-8'],
+ alignItems: 'flex-start',
+ },
+ search: {
+ width: 360,
+ },
});
diff --git a/docs/specs/components/PowerSearch/PowerSearch.spec.md b/docs/specs/components/PowerSearch/PowerSearch.spec.md
index 99fb9086c2..2fd68ee52b 100644
--- a/docs/specs/components/PowerSearch/PowerSearch.spec.md
+++ b/docs/specs/components/PowerSearch/PowerSearch.spec.md
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, accessibility]
verified_by:
[
packages/core/src/PowerSearch/PowerSearch.test.tsx,
+ packages/core/src/PowerSearch/PowerSearch.calendarSystems.test.tsx,
packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx,
packages/core/src/PowerSearch/PowerSearchDateZone.test.tsx,
packages/core/src/PowerSearch/PowerSearchDateTime.test.tsx,
@@ -40,6 +41,7 @@ architecture:
contributing: []
system_specs:
[
+ spec:AST-013/FR12,
spec:AST-017/FR3,
spec:AST-017/FR27,
spec:AST-020/FR15,
@@ -85,6 +87,13 @@ present-tense implementation gap note.
change with no public API change. DEC-3 adds the stable `presentation` prop
and its `adaptive` default, as the two DEC-3 bullets below state.
- Controlled/uncontrolled behavior: unchanged.
+- Calendar: date values follow the provider's calendar. A provider locale with a
+ `-u-ca-` keyword keeps Gregorian dates (`spec:AST-111` DEC-2); set the
+ provider's `calendar` to choose one. Implementation gap: a date value's
+ editor is a `DateInput`, or a `DateRangeInput` for a `date_range` value, and
+ shows the calendar that input resolves, which is Gregorian; under a provider
+ calendar such as `persian`, a date token and its editor name one day in two
+ calendars.
- Migration decisions: `component:PowerSearch/DEC-1`,
`component:PowerSearch/DEC-2`, and, for the `adaptive` default,
`presentation="popover"` (below).
@@ -509,6 +518,34 @@ no theming target or theme state; the root element keeps the existing
takes because the shared page-body channel is not exposed there.
- `spec:AST-017/FR3` governs the default change.
+### `spec:AST-013` FR12 exception — calendars that need `Temporal`
+
+- **Capability:** date values that PowerSearch (its tokens in both
+ presentations, and the sheet's Filters rows and removal announcement) and
+ PowerSearchToken write in the provider's calendar (`spec:AST-111` FR18), for
+ calendars other than `gregory`, `iso8601`, `buddhist`, `roc`, and
+ `japanese`, which need the runtime's `Temporal`.
+- **Reduction:** where `Temporal` is missing or does not support the calendar,
+ as in Safari on macOS and iOS, such a calendar resolves to `gregory` before
+ the first render and warns once in development, on the server and in the
+ browser, naming `temporal-polyfill/full/global` (`spec:AST-111` FR5). Date
+ values then show Gregorian dates; filter values stay Unix seconds. An
+ application that loads a `Temporal` polyfill gets the full calendar. A
+ server without `Temporal` renders Gregorian text, which a browser with
+ `Temporal` does not match, so a server-rendered application loads `Temporal`
+ on the server too.
+- **Preserved obligations:** `spec:AST-013` FR7 and FR8, and FR9 whenever the
+ server and the browser resolve the calendar the same way, outside the
+ `chinese` and `dangi` case of `spec:AST-111` FR19. The filter flow and the
+ filter values do not change; nothing throws.
+- **Evidence:** `PowerSearch.calendarSystems.test.tsx` with a `Temporal`
+ polyfill and with `Temporal` removed; `PowerSearchBottomSheet.test.tsx`
+ ("writes the trigger token and the Filters row in the provider calendar").
+ Evidence gap: no real-browser run, and no server render and hydration test,
+ under a calendar that needs `Temporal`.
+- **Owner:** `nynexman4464`.
+- **Review condition:** Safari ships `Temporal`.
+
### Current dependency
`component:Tokenizer` is current authority on `main` and satisfies PowerSearch's
diff --git a/docs/specs/components/Timestamp/Timestamp.spec.md b/docs/specs/components/Timestamp/Timestamp.spec.md
index b0bbec4193..662c3e919d 100644
--- a/docs/specs/components/Timestamp/Timestamp.spec.md
+++ b/docs/specs/components/Timestamp/Timestamp.spec.md
@@ -31,22 +31,22 @@ architecture:
architecture:react-component-runtime,
]
contributing: []
-system_specs: [spec:AST-009, spec:AST-085]
+system_specs: [spec:AST-009, spec:AST-013/FR12, spec:AST-085, spec:AST-111/FR18]
---
# Timestamp component contract
## Contract at a glance
-| Area | Contract |
-| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Public contract | A `time` element for a `value` (Unix seconds, milliseconds, or ISO 8601) in one of twelve `format`s, with optional live updates, time-zone suffix, and a copyable hover card. |
-| Behavior | Relative output carries the full absolute date as its default accessible name; relative output, or configured `tooltipEntries`, attach a keyboard-reachable hover card of copyable rows. |
-| End-user impact | Readers see compact or exact times in their locale; screen-reader users hear the full date and time zone; keyboard users can open and copy the exact time. |
-| Builder impact | None; the record describes shipped behavior. |
-| Compatibility/readiness | Released behavior recorded as current; no API, default, or output changes. Three implementation gaps are listed under Current-state impact. |
-| Review checks | Reject a relative timestamp without the full absolute name when the caller names nothing, a hover card without a tab stop, a change that makes more server markup depend on the server's zone, or a crash on an unparseable value. |
-| Governing rules | `architecture:internationalization/INV4,INV8,INV10`; `architecture:react-component-runtime/INV1,INV3,INV5`; `architecture:public-component-api/INV5,INV6,INV8`. |
+| Area | Contract |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | A `time` element for a `value` (Unix seconds, milliseconds, or ISO 8601) in one of twelve `format`s, with optional live updates, time-zone suffix, and a copyable hover card. |
+| Behavior | Relative output carries the full absolute date as its default accessible name; relative output, or configured `tooltipEntries`, attach a keyboard-reachable hover card of copyable rows. |
+| End-user impact | Readers see compact or exact times in their locale; screen-reader users hear the full date and time zone; keyboard users can open and copy the exact time. |
+| Builder impact | Optional: set `calendar` on the `InternationalizationProvider` to write dates in another calendar. |
+| Compatibility/readiness | No API or default changes. Without a provider calendar the output is unchanged; under one, date-bearing formats change calendar, and calendars that need `Temporal` fall back to Gregorian where it is missing (the `spec:AST-013` FR12 exception). A provider locale with a `-u-ca-` keyword keeps Gregorian dates (`spec:AST-111` DEC-2); set the provider's `calendar` to choose one. Three implementation gaps are listed under Current-state impact. |
+| Review checks | Reject a relative timestamp without the full absolute name when the caller names nothing, a hover card without a tab stop, a change that makes more server markup depend on the server's zone, or a crash on an unparseable value. |
+| Governing rules | `architecture:internationalization/INV4,INV8,INV10`; `spec:AST-111/FR18`; `spec:AST-013` FR12; `architecture:react-component-runtime/INV1,INV3,INV5`; `architecture:public-component-api/INV5,INV6,INV8`. |
This table is a review projection; the body below is authoritative.
@@ -60,8 +60,11 @@ the exact time.
## Compatibility and migration
- Released default preserved: `yes`
-- Compatibility class: records shipped behavior; no public prop, default, DOM,
- or styling output changes
+- Compatibility class: no public prop, default, DOM, or styling change;
+ date-bearing text follows the provider's calendar, which is Gregorian unless
+ the application selects another. A provider locale with a `-u-ca-` keyword
+ keeps Gregorian dates (`spec:AST-111` DEC-2); set the provider's `calendar` to
+ choose one
- Controlled/uncontrolled behavior: not applicable; the current clock is
internal state
- Migration decision: none
@@ -118,17 +121,17 @@ Consumer migration instructions belong in consumer docs and release notes.
## Behavioral and layout contract
-| ID | Invariant | Basis |
-| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
-| FR1 | Timestamp renders a Text element (default `type="supporting"`, `color="secondary"`, with `size` and `weight` passed through) carrying the `timestamp` target, which reflects the resolved format beside Text's type and color reflection; inside it an inline `time` element inherits the typography and carries the instant's ISO 8601 `datetime`. An unparseable value renders nothing and logs a development warning. | Current source and tests |
-| FR2 | `auto` shows `relative` when the instant is within `autoThreshold` seconds of now (default seven days) and `date_time` otherwise. `relative` uses the locale's long relative phrase and `relative_short` its narrow phrase; a value a few seconds in the future reads as "now". Absolute formats use the shared instant formatter in the provider locale with Gregorian years; `system_*` formats are machine-readable, and `unix_seconds` is zone-independent. `isTimezoneShown` appends the zone abbreviation to `date_time` and `time` only. | Current source and tests |
-| FR3 | Server markup does not depend on the server's time zone and hydrates without a mismatch. A format that needs the clock renders `date_time` in UTC with the zone shown until the client can read the clock; the client then shows the resolved format without committing the UTC placeholder. Implementation gap: absolute formats other than `unix_seconds` render in the host's time zone, so their server markup depends on the server's zone and hydrating it in another zone produces a text mismatch (Current-state impact). | Current source and tests |
-| FR4 | With `isLive` and relative output, the clock refreshes every second under a minute old, every 30 seconds under an hour, every minute under a day, and every five minutes beyond; the timer is cleared on unmount or when the inputs change. Locale changes update the output live. | Current source and tests |
-| FR5 | Relative output is named by the full absolute date and the long time-zone name unless a caller names the element; absolute output adds no name. A caller's explicit `aria-label` reaches the element (`architecture:public-component-api` INV5). | Current source and tests |
-| FR6 | When `hasTooltip` is true and the output is relative or `tooltipEntries` is non-empty, a lazily loaded HoverCard named "Timestamp details" attaches above the timestamp, opening on hover and on keyboard focus; the `time` element gains `tabIndex={0}`. Otherwise no card renders and no tab stop is added. Focus placed on the timestamp stays there when the card attaches (`spec:AST-085` FR4). Implementation gap: while the card module loads, a fallback `time` with the tab stop renders, and attaching the card replaces it, so focus placed on it falls to the page body and no card opens (Current-state impact). | Current source and tests |
-| FR7 | The card is a description list in a grid: an optional label column (present when any row has a label), the value column, and a trailing action column (present when any row is copyable). Without entries it has one copyable row with the full absolute time in the viewer's zone. Each configured entry is one row in the given order, rendered in its own time zone and format, read-only unless `isCopyable`. An unknown time zone does not crash. A description list holds only name-value groups (WCAG 2.2 1.3.1). Implementation gaps: once any row is copyable, every row carries an action-cell `div` inside its row group (empty on read-only rows), so the open card fails the `definition-list` structure check, and a card with no labelled rows, the default card included, renders each row as a lone `dd` with no `dt` (Current-state impact). | Current source and tests |
-| FR8 | A copy button is a small ghost IconButton on the `timestamp-copy-button` target, named "Copy {value}" with a "Copy" tooltip; activating it writes the row's value to the clipboard, switches to a check icon and the "Copied" name and tooltip for 1.5 seconds, and announces "Copied" politely. A clipboard rejection does nothing. | Current source and tests |
-| FR9 | `ref`, `data-testid`, and other supported DOM, ARIA, data, and event props reach the `time` element; `xstyle`, `className`, and `style` reach the Text wrapper. A caller `aria-labelledby` names the element in place of FR5's name. A caller's explicit `tabIndex` reaches the element (`architecture:public-component-api` INV5). | Current source and tests |
+| ID | Invariant | Basis |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
+| FR1 | Timestamp renders a Text element (default `type="supporting"`, `color="secondary"`, with `size` and `weight` passed through) carrying the `timestamp` target, which reflects the resolved format beside Text's type and color reflection; inside it an inline `time` element inherits the typography and carries the instant's ISO 8601 `datetime`. An unparseable value renders nothing and logs a development warning. | Current source and tests |
+| FR2 | `auto` shows `relative` when the instant is within `autoThreshold` seconds of now (default seven days) and `date_time` otherwise. `relative` uses the locale's long relative phrase and `relative_short` its narrow phrase; a value a few seconds in the future reads as "now". Absolute formats use the shared instant formatter in the provider locale. The date-bearing formats (`date`, `date_long`, `date_weekday`, `date_time`, and the full date of FR5 and FR7) write the date in the calendar that the provider resolves (`spec:AST-111` FR2, FR5, FR18), which is Gregorian unless the application selects another; a locale's default calendar never applies, and `date_time` keeps its time of day. Each names the month and day that `component:Calendar` shows. `time`, the relative formats, `system_*`, and `unix_seconds` do not depend on the calendar. `system_*` formats are machine-readable Gregorian ISO, and `unix_seconds` is zone-independent. `isTimezoneShown` appends the zone abbreviation to `date_time` and `time` only. | Current source and tests |
+| FR3 | Server markup does not depend on the server's time zone and hydrates without a mismatch. A format that needs the clock renders `date_time` in UTC and the Gregorian calendar with the zone shown until the client can read the clock; the client then shows the resolved format without committing the UTC placeholder. A calendar that needs `Temporal` hydrates without a mismatch only when the server and the browser resolve it the same way (the `spec:AST-013` FR12 exception). Implementation gap: absolute formats other than `unix_seconds` render in the host's time zone, so their server markup depends on the server's zone and hydrating it in another zone produces a text mismatch (Current-state impact). | Current source and tests |
+| FR4 | With `isLive` and relative output, the clock refreshes every second under a minute old, every 30 seconds under an hour, every minute under a day, and every five minutes beyond; the timer is cleared on unmount or when the inputs change. Locale changes update the output live. | Current source and tests |
+| FR5 | Relative output is named by the full absolute date and the long time-zone name unless a caller names the element; absolute output adds no name. A caller's explicit `aria-label` reaches the element (`architecture:public-component-api` INV5). | Current source and tests |
+| FR6 | When `hasTooltip` is true and the output is relative or `tooltipEntries` is non-empty, a lazily loaded HoverCard named "Timestamp details" attaches above the timestamp, opening on hover and on keyboard focus; the `time` element gains `tabIndex={0}`. Otherwise no card renders and no tab stop is added. Focus placed on the timestamp stays there when the card attaches (`spec:AST-085` FR4). Implementation gap: while the card module loads, a fallback `time` with the tab stop renders, and attaching the card replaces it, so focus placed on it falls to the page body and no card opens (Current-state impact). | Current source and tests |
+| FR7 | The card is a description list in a grid: an optional label column (present when any row has a label), the value column, and a trailing action column (present when any row is copyable). Without entries it has one copyable row with the full absolute time in the viewer's zone. Each configured entry is one row in the given order, rendered in its own time zone and format, read-only unless `isCopyable`. An unknown time zone does not crash. A description list holds only name-value groups (WCAG 2.2 1.3.1). Implementation gaps: once any row is copyable, every row carries an action-cell `div` inside its row group (empty on read-only rows), so the open card fails the `definition-list` structure check, and a card with no labelled rows, the default card included, renders each row as a lone `dd` with no `dt` (Current-state impact). | Current source and tests |
+| FR8 | A copy button is a small ghost IconButton on the `timestamp-copy-button` target, named "Copy {value}" with a "Copy" tooltip; activating it writes the row's value to the clipboard, switches to a check icon and the "Copied" name and tooltip for 1.5 seconds, and announces "Copied" politely. A clipboard rejection does nothing. | Current source and tests |
+| FR9 | `ref`, `data-testid`, and other supported DOM, ARIA, data, and event props reach the `time` element; `xstyle`, `className`, and `style` reach the Text wrapper. A caller `aria-labelledby` names the element in place of FR5's name. A caller's explicit `tabIndex` reaches the element (`architecture:public-component-api` INV5). | Current source and tests |
### Allowed variation
@@ -147,6 +150,7 @@ Consumer migration instructions belong in consumer docs and release notes.
| Server render | Markup identical across server zones; clock-dependent formats show UTC `date_time` with zone (absolute formats use the server's zone today, the FR3 gap). | — |
| Live | Relative phrase refreshes at the tier's interval. | — |
| Unparseable | Nothing rendered; development warning. | — |
+| Provider calendar | Date-bearing output, the card's full date, and the relative name in that calendar; `date_time` keeps its time; `system_*` stays Gregorian ISO. | Calendar, locale. |
| `hasTooltip={false}` | No card and no tab stop, even with entries. | — |
### Transformation and precedence order
@@ -210,27 +214,55 @@ Consumer migration instructions belong in consumer docs and release notes.
## Family and system relationships
- `architecture:internationalization` owns locale resolution, live locale
- changes, the shared formatter, and Gregorian defaults; FR2 and FR4 rely on
- them.
+ changes, the shared formatter, and calendar resolution with its Gregorian
+ default; `spec:AST-111` FR18 sets which formats follow the calendar. FR2 and
+ FR4 rely on them.
- `architecture:react-component-runtime` owns valid initial render and timer
cleanup; FR3 and FR4 apply them.
- HoverCard owns the card surface; Timestamp supplies its content, name, and
trigger focusability.
+### `spec:AST-013` FR12 exception — calendars that need `Temporal`
+
+- **Capability:** date-bearing output in calendars other than `gregory`,
+ `iso8601`, `buddhist`, `roc`, and `japanese`, which need the runtime's
+ `Temporal`.
+- **Reduction:** where `Temporal` is missing or does not support the calendar,
+ as in Safari on macOS and iOS, such a calendar resolves to `gregory` before
+ the first render and warns once in development, on the server and in the
+ browser, naming `temporal-polyfill/full/global` (`spec:AST-111` FR5). The
+ date-bearing formats, the card's full date, and the relative name then write
+ Gregorian dates. An application that loads a `Temporal` polyfill gets the
+ full calendar. A server without `Temporal` renders Gregorian text, which a
+ browser with `Temporal` does not match, so a server-rendered application
+ loads `Temporal` on the server too.
+- **Preserved obligations:** `spec:AST-013` FR7 and FR8, and FR9 whenever the
+ server and the browser resolve the calendar the same way, outside the
+ `chinese` and `dangi` case of `spec:AST-111` FR19. The Gregorian output keeps
+ the instant, its accessible name, the hover card, and copying; nothing
+ throws.
+- **Evidence:** `Timestamp.test.tsx` calendar-system tests with a `Temporal`
+ polyfill and with `Temporal` removed, and "hydrates a clock format rendered
+ on a server without Temporal". Evidence gap: no real-browser run, and no
+ hydration test of an absolute date format, under a calendar that needs
+ `Temporal`.
+- **Owner:** `nynexman4464`.
+- **Review condition:** Safari ships `Temporal`.
+
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
-| FR1, FR2 | `Timestamp.test.tsx` format, auto, locale, and invalid-value tests; stable visual baseline `core-timestamp--default` | Every format; thresholds; locales; unparseable values; default | A wrong phrase, a crossed tier, a non-Gregorian year, a missing `time` element or `datetime`, a crash, or a missing development warning for an unparseable value fails; a changed default type or color comes back changed for review. Gap: no test asserts the `timestamp` target or its format reflection. | `audit:Timestamp/behavior` |
-| FR3 | `Timestamp.test.tsx` server-rendering suite | Server zones; hydration | Zone-dependent markup, a hydration mismatch, or a committed placeholder fails. Gap: no test covers an absolute format rendered on a server in another zone. | `audit:Timestamp/behavior` |
-| FR4, PR1 | `Timestamp.test.tsx` live-update and locale tests | Live relative output; locale change | A missing refresh or a stale locale fails. Gap: the per-tier refresh intervals and the timer cleanup on unmount or input change have no automated check. | `audit:Timestamp/behavior` |
-| FR5, AR2 | `Timestamp.test.tsx` naming tests | Relative, absolute, time-zone spelling | A missing or short-zone name, or a name on absolute output, fails. A caller `aria-label` replaced on relative output fails. | `audit:Timestamp/a11y` |
-| FR6, AR3 | `Timestamp.test.tsx` keyboard-reachability suite | Relative, absolute, disabled, entries removed | A missing tab stop, `aria-expanded` on the trigger, or a stray tab stop fails. The aria-expanded test also pins `aria-haspopup` on the Text wrapper, which is current behavior, not contract. Gap: no test covers focus on the timestamp while the card module loads, or `aria-controls`. | `audit:Timestamp/a11y` |
-| FR7, FR8, AR4 | `Timestamp.test.tsx` hover-card suites; `tooltipEntries.test.ts`; `useClipboard.test.tsx` | Default row, entries, copyable rows, unknown zone | A wrong row count or order, an unpaired label, a copy button on a read-only row, a wrong copied value, a missing copied state, or a missing announcement fails. Gap: no check runs the `definition-list` structure rule on the open card (the recorded gap); the grid columns and the 1.5-second reset have no automated check; `useClipboard.test.tsx` covers the clipboard-rejection no-op. The lone-`dd` rows of a label-less card are also unchecked. | `audit:Timestamp/behavior` |
-| FR9 | `Timestamp.test.tsx` ref, test-id, and pass-through tests | Ref, test id, caller props | A ref, test id, or caller prop missing from the `time` element fails. A caller `tabIndex` replaced while a card is attached fails. Gap: no test asserts that `xstyle`, `className`, and `style` reach the Text wrapper, or covers a caller `aria-labelledby`. | `audit:Timestamp/behavior` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy, targets, HoverCard delegate | Missing, extra, or stale mappings fail repository validation. | `audit:Timestamp/theming` |
-| AR1 | `Timestamp.test.tsx` `datetime` tests | `date_time`; `date` | A missing or wrong ISO `datetime` on `date_time`, or a missing one on `date`, fails. Gap: no test asserts the exact `datetime` on relative or other absolute formats. | `audit:Timestamp/a11y` |
-| AR2, AR4 | Accessibility-tree evidence (`spec:AST-009` FR3) | Relative output; copy buttons | Gap: no accessibility-tree check proves the computed name of relative output or the copy-button names; the unit tests query the DOM. | `audit:Timestamp/a11y` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- |
+| FR1, FR2 | `Timestamp.test.tsx` format, auto, locale, calendar-system, and invalid-value tests; `tooltipEntries.test.ts` calendar tests; stable visual baseline `core-timestamp--default` | Every format; thresholds; locales; `persian`, `hebrew`, and `buddhist` under English and native locales, with and without `Temporal`; `iso8601`; `chinese` where `Intl` and `Temporal` disagree; unparseable values; default | A wrong phrase, a crossed tier, a non-Gregorian year without a provider calendar, a date-bearing format that ignores the provider calendar or names another day than `component:Calendar`, a changed `system_*` or `time` output, a missing `time` element or `datetime`, a crash, or a missing development warning for an unparseable value fails; a changed default type or color comes back changed for review. Gap: no test asserts the `timestamp` target or its format reflection. | `audit:Timestamp/behavior` |
+| FR3 | `Timestamp.test.tsx` server-rendering suite and "hydrates a clock format rendered on a server without Temporal" | Server zones; hydration | Zone-dependent markup, a hydration mismatch, or a committed placeholder fails. Gap: no test covers an absolute format rendered on a server in another zone. | `audit:Timestamp/behavior` |
+| FR4, PR1 | `Timestamp.test.tsx` live-update and locale tests | Live relative output; locale change | A missing refresh or a stale locale fails. Gap: the per-tier refresh intervals and the timer cleanup on unmount or input change have no automated check. | `audit:Timestamp/behavior` |
+| FR5, AR2 | `Timestamp.test.tsx` naming tests | Relative, absolute, time-zone spelling | A missing or short-zone name, or a name on absolute output, fails. A caller `aria-label` replaced on relative output fails. | `audit:Timestamp/a11y` |
+| FR6, AR3 | `Timestamp.test.tsx` keyboard-reachability suite | Relative, absolute, disabled, entries removed | A missing tab stop, `aria-expanded` on the trigger, or a stray tab stop fails. The aria-expanded test also pins `aria-haspopup` on the Text wrapper, which is current behavior, not contract. Gap: no test covers focus on the timestamp while the card module loads, or `aria-controls`. | `audit:Timestamp/a11y` |
+| FR7, FR8, AR4 | `Timestamp.test.tsx` hover-card suites; `tooltipEntries.test.ts`; `useClipboard.test.tsx` | Default row, entries, copyable rows, unknown zone | A wrong row count or order, an unpaired label, a copy button on a read-only row, a wrong copied value, a missing copied state, or a missing announcement fails. Gap: no check runs the `definition-list` structure rule on the open card (the recorded gap); the grid columns and the 1.5-second reset have no automated check; `useClipboard.test.tsx` covers the clipboard-rejection no-op. The lone-`dd` rows of a label-less card are also unchecked. | `audit:Timestamp/behavior` |
+| FR9 | `Timestamp.test.tsx` ref, test-id, and pass-through tests | Ref, test id, caller props | A ref, test id, or caller prop missing from the `time` element fails. A caller `tabIndex` replaced while a card is attached fails. Gap: no test asserts that `xstyle`, `className`, and `style` reach the Text wrapper, or covers a caller `aria-labelledby`. | `audit:Timestamp/behavior` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Consumer anatomy, targets, HoverCard delegate | Missing, extra, or stale mappings fail repository validation. | `audit:Timestamp/theming` |
+| AR1 | `Timestamp.test.tsx` `datetime` tests | `date_time`; `date` | A missing or wrong ISO `datetime` on `date_time`, or a missing one on `date`, fails. Gap: no test asserts the exact `datetime` on relative or other absolute formats. | `audit:Timestamp/a11y` |
+| AR2, AR4 | Accessibility-tree evidence (`spec:AST-009` FR3) | Relative output; copy buttons | Gap: no accessibility-tree check proves the computed name of relative output or the copy-button names; the unit tests query the DOM. | `audit:Timestamp/a11y` |
## Decision log
diff --git a/packages/charts/src/formatters.test.ts b/packages/charts/src/formatters.test.ts
index a42f8c8ac3..113ee23cfd 100644
--- a/packages/charts/src/formatters.test.ts
+++ b/packages/charts/src/formatters.test.ts
@@ -86,6 +86,45 @@ describe('chart formatters', () => {
);
});
+ it.each([
+ {calendar: 'persian', locale: 'en', year: '1405'},
+ {calendar: 'persian', locale: 'fa', year: '۱۴۰۵'},
+ {calendar: 'hebrew', locale: 'en', year: '5787'},
+ {calendar: 'hebrew', locale: 'he', year: '5787'},
+ {calendar: 'buddhist', locale: 'en', year: '2569'},
+ {calendar: 'buddhist', locale: 'th', year: '2569'},
+ ] as const)(
+ 'formats dates in an explicit $calendar calendar under $locale',
+ ({calendar, locale, year}) => {
+ const value = '2026-10-30';
+ const date = new Date(2026, 9, 30);
+ expect(shortDate(value, locale, calendar)).toBe(
+ new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ day: 'numeric',
+ calendar,
+ }).format(date),
+ );
+ const label = monthYear(value, locale, calendar);
+ expect(label).toBe(
+ new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ year: 'numeric',
+ calendar,
+ }).format(date),
+ );
+ expect(label).toContain(year);
+ expect(label).not.toContain('2026');
+ },
+ );
+
+ it('defaults to Gregorian and writes `iso8601` dates as Gregorian ones', () => {
+ const value = '2026-10-30';
+ expect(monthYear(value, 'en')).toBe('Oct 2026');
+ expect(monthYear(value, 'en', 'iso8601')).toBe('Oct 2026');
+ expect(shortDate(value, 'en', 'iso8601')).toBe(shortDate(value, 'en'));
+ });
+
it('passes through non-finite and unparseable values', () => {
expect(compactNumber(Infinity, 'en-US')).toBe('Infinity');
expect(percent('not-a-number', 'en-US')).toBe('not-a-number');
diff --git a/packages/charts/src/formatters.ts b/packages/charts/src/formatters.ts
index e4186fed07..d1e44deb16 100644
--- a/packages/charts/src/formatters.ts
+++ b/packages/charts/src/formatters.ts
@@ -2,6 +2,7 @@
/**
* @file formatters.ts
+ * @input Values, a provider locale, and for dates an optional calendar
* @output Built-in locale-aware tick, value, and list format utilities
* @position Utility; consumed by Chart and ChartAxis
*
@@ -12,7 +13,8 @@
* across the full magnitude range (K/M/B/T and beyond).
*/
-import type {Locale} from '@astryxdesign/core/i18n';
+import type {CalendarSystem, Locale} from '@astryxdesign/core/i18n';
+import {plainDateFormat, plainDateFromDate} from '@astryxdesign/core/utils';
/** Lazily cache one formatter per locale, including the legacy host default. */
function byLocale<T>(
@@ -179,20 +181,48 @@ function toDate(value: unknown): Date {
return new Date(NaN);
}
-/** Date formatter — short date (e.g. "Jan 5", "Mar 12"). */
-export function shortDate(value: unknown, locale: Locale): string {
+/**
+ * Date formatter — short date (e.g. "Jan 5", "Mar 12"), in `calendar`. The
+ * calendar defaults to Gregorian; pass the application's calendar to match
+ * the date components.
+ */
+export function shortDate(
+ value: unknown,
+ locale: Locale,
+ calendar: CalendarSystem = 'gregory',
+): string {
const d = toDate(value);
if (Number.isNaN(d.getTime())) {
return String(value);
}
- return getShortDateFormat(locale).format(d);
+ return calendar === 'gregory'
+ ? getShortDateFormat(locale).format(d)
+ : plainDateFormat(
+ plainDateFromDate(d),
+ {month: 'short', day: 'numeric', calendar},
+ locale,
+ );
}
-/** Date formatter — month/year (e.g. "Jan 2024", "Mar 2025"). */
-export function monthYear(value: unknown, locale: Locale): string {
+/**
+ * Date formatter — month/year (e.g. "Jan 2024", "Mar 2025"), in `calendar`.
+ * The calendar defaults to Gregorian; pass the application's calendar to
+ * match the date components.
+ */
+export function monthYear(
+ value: unknown,
+ locale: Locale,
+ calendar: CalendarSystem = 'gregory',
+): string {
const d = toDate(value);
if (Number.isNaN(d.getTime())) {
return String(value);
}
- return getMonthYearFormat(locale).format(d);
+ return calendar === 'gregory'
+ ? getMonthYearFormat(locale).format(d)
+ : plainDateFormat(
+ plainDateFromDate(d),
+ {month: 'short', year: 'numeric', calendar},
+ locale,
+ );
}
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 1efd917e7e..7b62073cbb 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -3013,7 +3013,7 @@ function formatDisplayTime12h: (time: ISOTimeString | undefined, includeSeconds?
function formatDisplayTime24h: (time: ISOTimeString | undefined, includeSeconds?: boolean) => string
function formatHex: (r: number, g: number, b: number) => string
function formatISOTime: (time: ParsedTime, includeSeconds?: boolean) => ISOTimeString
-function formatSharedDate: (pd: PlainDate, format: SharedDateFormat, locale?: Locale) => string
+function formatSharedDate: (pd: PlainDate, format: SharedDateFormat, locale?: Locale, calendar?: CalendarSystem) => string
function generateAdaptationCSS: (theme: DefinedTheme, warnings?: string[]) => ThemeCSSOutput
function generateColumns: <T extends Record<string, unknown>>(data: T[]) => TableColumn<T>[]
function generateOnMediaCSS: (theme: DefinedTheme, warnings?: string[]) => string
@@ -8272,7 +8272,7 @@ usePowerSearchConfig (.)
### Functions
```text
-function formatFilterValue: (_config: InternalConfig, operatorValue: OperatorValue, filterValue: FilterValue, maxLength: number, t: TranslatorFn, locale: Locale, timezoneID?: string) => string
+function formatFilterValue: (_config: InternalConfig, operatorValue: OperatorValue, filterValue: FilterValue, maxLength: number, t: TranslatorFn, locale: Locale, timezoneID?: string, calendar?: CalendarSystem) => string
```
### Types
diff --git a/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx b/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx
index 01d9459bb3..266d781e16 100644
--- a/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx
+++ b/packages/core/src/Calendar/Calendar.calendarSystems.test.tsx
@@ -22,6 +22,7 @@ import {
} from '../DateTimeInput/DateTimeInput';
import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {withChineseTemporalAheadOfIntl} from '../__tests__/temporalAheadOfIntl';
afterEach(() => {
__resetLiveRegionsForTest();
@@ -227,62 +228,6 @@ describe('Calendar in the Ethiopic calendar', () => {
});
});
-interface TestPlainDate {
- readonly year: number;
- readonly month: number;
- readonly day: number;
- readonly daysInMonth: number;
- with(fields: {day: number}): TestPlainDate;
- add(duration: object): TestPlainDate;
- subtract(duration: object): TestPlainDate;
- withCalendar(calendar: string): TestPlainDate;
-}
-
-type TestPlainDateConstructor = new (
- isoYear: number,
- isoMonth: number,
- isoDay: number,
- calendar: string,
-) => TestPlainDate;
-
-/**
- * Runs `run` with a Temporal whose Chinese calendar is one day ahead of
- * Intl's, as native Temporal is at some month starts, such as 2027-02-06.
- */
-function withChineseTemporalAheadOfIntl(run: () => void) {
- const globals = globalThis as unknown as {
- Temporal: {PlainDate: TestPlainDateConstructor};
- };
- const real = globals.Temporal;
- const shift = (inner: TestPlainDate): TestPlainDate => ({
- year: inner.year,
- month: inner.month,
- day: inner.day,
- daysInMonth: inner.daysInMonth,
- with: fields => shift(inner.with(fields)),
- add: duration => shift(inner.add(duration)),
- subtract: duration => shift(inner.subtract(duration)),
- withCalendar: calendar => inner.withCalendar(calendar).subtract({days: 1}),
- });
- function PlainDate(y: number, m: number, d: number, calendar: string) {
- return calendar === 'chinese'
- ? shift(
- new real.PlainDate(y, m, d, 'iso8601')
- .add({days: 1})
- .withCalendar('chinese'),
- )
- : new real.PlainDate(y, m, d, calendar);
- }
- globals.Temporal = {
- PlainDate: PlainDate as unknown as TestPlainDateConstructor,
- };
- try {
- run();
- } finally {
- globals.Temporal = real;
- }
-}
-
describe('Calendar in the Chinese calendar', () => {
it('names each day by the month and day the grid shows when Intl disagrees', () => {
withChineseTemporalAheadOfIntl(() => {
diff --git a/packages/core/src/PowerSearch/PowerSearch.calendarSystems.test.tsx b/packages/core/src/PowerSearch/PowerSearch.calendarSystems.test.tsx
new file mode 100644
index 0000000000..ad71820476
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearch.calendarSystems.test.tsx
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file PowerSearch.calendarSystems.test.tsx
+ * @input PowerSearch, PowerSearchToken, InternationalizationProvider, the
+ * full Temporal polyfill
+ * @output Tests that date values follow the provider's calendar
+ * @position Colocated tests; the polyfill stands in for the native Temporal of
+ * a supporting runtime
+ */
+
+import 'temporal-polyfill/full/global';
+import {afterAll, afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {PowerSearch} from './PowerSearch';
+import {PowerSearchToken} from './PowerSearchToken';
+import {formatDateAbsolute} from './formatFilterValue';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import type {CalendarSystem} from '../utils/calendarSystem';
+import {__resetDevWarnings} from '../utils/devWarning';
+import {withChineseTemporalAheadOfIntl} from '../__tests__/temporalAheadOfIntl';
+import type {
+ PowerSearchConfig,
+ PowerSearchField,
+ PowerSearchFilter,
+ PowerSearchOperator,
+} from './types';
+
+const UNIX_SECONDS = Date.parse('2026-10-30T12:00:00Z') / 1000;
+
+const isOperator: PowerSearchOperator = {
+ key: 'is',
+ label: 'is',
+ value: {type: 'date_absolute'},
+};
+
+const createdField: PowerSearchField = {
+ key: 'created',
+ label: 'Created',
+ defaultOperator: 'is',
+ operators: [isOperator],
+};
+
+const config: PowerSearchConfig = {name: 'Dates', fields: [createdField]};
+
+const filter: PowerSearchFilter = {
+ field: 'created',
+ operator: 'is',
+ value: {type: 'date_absolute', unixSeconds: UNIX_SECONDS},
+};
+
+function renderSearch(provider: {locale: string; calendar?: CalendarSystem}) {
+ return render(
+ <InternationalizationProvider {...provider}>
+ <PowerSearch config={config} filters={[filter]} onChange={() => {}} />
+ </InternationalizationProvider>,
+ );
+}
+
+function renderToken(provider: {locale: string; calendar?: CalendarSystem}) {
+ return render(
+ <InternationalizationProvider {...provider}>
+ <PowerSearchToken
+ config={config}
+ filter={filter}
+ field={createdField}
+ operator={isOperator}
+ maxLength={60}
+ />
+ </InternationalizationProvider>,
+ );
+}
+
+afterEach(() => {
+ __resetDevWarnings();
+ vi.restoreAllMocks();
+});
+
+describe('PowerSearch date values in the provider calendar', () => {
+ it.each([
+ {calendar: 'persian', locale: 'en', year: '1405'},
+ {calendar: 'persian', locale: 'fa', year: '۱۴۰۵'},
+ {calendar: 'hebrew', locale: 'en', year: '5787'},
+ {calendar: 'hebrew', locale: 'he', year: '5787'},
+ {calendar: 'buddhist', locale: 'en', year: '2569'},
+ {calendar: 'buddhist', locale: 'th', year: '2569'},
+ ] as const)(
+ 'writes the token value in $calendar under $locale',
+ ({calendar, locale, year}) => {
+ renderSearch({locale, calendar});
+ const expected = formatDateAbsolute(
+ UNIX_SECONDS,
+ locale,
+ undefined,
+ true,
+ calendar,
+ );
+ expect(expected).toContain(year);
+ expect(screen.getByText(expected)).toBeInTheDocument();
+ },
+ );
+
+ it('keeps Gregorian dates without a provider calendar', () => {
+ renderSearch({locale: 'fa-IR'});
+ expect(
+ screen.getByText(formatDateAbsolute(UNIX_SECONDS, 'fa-IR', undefined)),
+ ).toBeInTheDocument();
+ });
+
+ it('writes the PowerSearchToken value in the provider calendar', () => {
+ renderToken({locale: 'en', calendar: 'persian'});
+ expect(screen.getByText(/Aban 8, 1405 AP/)).toBeInTheDocument();
+ });
+
+ it('writes a date and time on the `chinese` day that Calendar shows', () => {
+ const lunarNewYear = Date.parse('2027-02-06T12:00:00Z') / 1000;
+ const value = withChineseTemporalAheadOfIntl(() =>
+ formatDateAbsolute(lunarNewYear, 'en', 'UTC', false, 'chinese'),
+ );
+ // Intl alone names the 30th day of the Twelfth Month of 2026.
+ expect(value).toMatch(/^Mo1 1, 2027, 12:00\sPM$/);
+ });
+
+ it('writes a date and time in `iso8601` as in `gregory`', () => {
+ expect(
+ formatDateAbsolute(UNIX_SECONDS, 'en', 'UTC', false, 'iso8601'),
+ ).toBe(formatDateAbsolute(UNIX_SECONDS, 'en', 'UTC', false));
+ });
+
+ describe('without Temporal', () => {
+ const globals = globalThis as {Temporal?: unknown};
+ let savedTemporal: unknown;
+
+ beforeAll(() => {
+ savedTemporal = globals.Temporal;
+ delete globals.Temporal;
+ });
+
+ afterAll(() => {
+ globals.Temporal = savedTemporal;
+ });
+
+ it('shows Gregorian dates for a calendar that needs Temporal', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ renderSearch({locale: 'en', calendar: 'persian'});
+ expect(
+ screen.getByText(formatDateAbsolute(UNIX_SECONDS, 'en', undefined)),
+ ).toBeInTheDocument();
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('needs a Temporal that supports it'),
+ );
+ });
+
+ it('still shows the buddhist calendar, which needs no Temporal', () => {
+ renderSearch({locale: 'en', calendar: 'buddhist'});
+ expect(
+ screen.getByText(
+ formatDateAbsolute(UNIX_SECONDS, 'en', undefined, true, 'buddhist'),
+ ),
+ ).toBeInTheDocument();
+ });
+ });
+});
diff --git a/packages/core/src/PowerSearch/PowerSearch.doc.mjs b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
index fbc32150d1..e95d631824 100644
--- a/packages/core/src/PowerSearch/PowerSearch.doc.mjs
+++ b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
@@ -142,7 +142,7 @@ export const docs = {
name: 'timezoneID',
type: 'string',
description:
- 'IANA zone a date-only date_absolute value, and each absolute part of a date_range, is read and written in: the day shows, edits and stores (as that midnight) in it; unset, a day is its UTC day. A date_absolute with isDateOnly: false shows and edits its date and time in it; unset, in the viewer\'s zone. E.g. "America/New_York".',
+ 'IANA zone a date-only date_absolute value, and each absolute part of a date_range, is read and written in: the day shows, edits and stores (as that midnight) in it; unset, a day is its UTC day. A date_absolute with isDateOnly: false shows and edits its date and time in it; unset, in the viewer\'s zone. E.g. "America/New_York". Date values are written in the InternationalizationProvider calendar, such as calendar="persian"; filter values stay Unix seconds. The value editor, a DateInput or DateRangeInput, shows the calendar that input resolves, which is Gregorian.',
},
{
name: 'handleRef',
@@ -450,7 +450,7 @@ export const docsZh = {
name: 'timezoneID',
type: 'string',
description:
- '仅日期的 date_absolute 值及 date_range 的每个绝对端点读写所用的 IANA 时区:该日在此时区显示、编辑并以其午夜存储;未设置时为 UTC 日。isDateOnly: false 的 date_absolute 值在此时区显示并编辑其日期和时间;未设置时为查看者所在时区。例如 "America/New_York"。',
+ '仅日期的 date_absolute 值及 date_range 的每个绝对端点读写所用的 IANA 时区:该日在此时区显示、编辑并以其午夜存储;未设置时为 UTC 日。isDateOnly: false 的 date_absolute 值在此时区显示并编辑其日期和时间;未设置时为查看者所在时区。例如 "America/New_York"。日期值使用 InternationalizationProvider 的历法(如 calendar="persian")显示;筛选值仍为 Unix 秒数。值编辑器(DateInput 或 DateRangeInput)显示该输入框解析的历法,即公历。',
},
{
name: 'handleRef',
@@ -572,7 +572,7 @@ export const docsDense = {
menuWidth: 'Main field/search menu width in pixels.',
popoverSaveButtonLabel: 'Label for save button in edit popover.',
timezoneID:
- 'IANA zone a date-only value reads and writes in; unset, its UTC day.',
+ 'IANA zone a date-only value reads and writes in; unset, its UTC day. Dates show in the provider calendar; their editor shows Gregorian dates.',
handleRef:
'Imperative handle w/ focusTypeahead() + blurTypeahead() methods.',
endContent:
diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsx
index 137a8ef2fb..39895dda6d 100644
--- a/packages/core/src/PowerSearch/PowerSearch.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.tsx
@@ -86,6 +86,7 @@ import {
import {resolveOperatorLabel} from './resolveOperatorLabel';
import {themeProps} from '../utils/themeProps';
import {useLocale} from '../i18n/useLocale';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
import type {Locale} from '../i18n/types';
import type {SearchableItem} from '../Typeahead/types';
import type {
@@ -599,6 +600,7 @@ export function PowerSearch({
const searchSource = usePowerSearchSource(config, maxSearchResults);
const t = useComponentTranslator();
const locale = useLocale();
+ const calendar = useCalendarSystem(undefined, 'PowerSearch');
const label = labelFromProps ?? t('@astryx.powersearch.label');
const placeholder =
placeholderFromProps ?? t('@astryx.powersearch.placeholder');
@@ -723,6 +725,7 @@ export function PowerSearch({
10,
),
locale,
+ calendar,
undefined,
undefined,
timezoneID,
@@ -730,7 +733,7 @@ export function PowerSearch({
: null;
return {label, value, full: value != null ? `${label} ${value}` : label};
},
- [config, maxTokenLength, t, locale, timezoneID],
+ [config, maxTokenLength, t, locale, timezoneID, calendar],
);
// The built-in token being edited. A token from a `components` override
// names itself, so its editor keeps the plain popover.
@@ -881,6 +884,7 @@ export function PowerSearch({
t,
locale,
timezoneID,
+ calendar,
)
: '';
@@ -899,7 +903,7 @@ export function PowerSearch({
},
};
});
- }, [filters, config, maxTokenLength, timezoneID, t, locale]);
+ }, [filters, config, maxTokenLength, timezoneID, t, locale, calendar]);
// Handle tokenizer onChange (field selected from typeahead)
const handleTokenizerChange = useCallback(
diff --git a/packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx b/packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx
index f0052e4bd3..1672f3f241 100644
--- a/packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx
@@ -5022,6 +5022,27 @@ describe('PowerSearch sheet value text', () => {
);
});
+ it('writes the trigger token and the Filters row in the provider calendar', () => {
+ // The buddhist calendar needs no Temporal.
+ render(
+ <InternationalizationProvider locale="en" calendar="buddhist">
+ <PowerSearch
+ config={valueTypesConfig}
+ filters={[dateFilter]}
+ onChange={() => {}}
+ presentation="bottom-sheet"
+ />
+ </InternationalizationProvider>,
+ );
+ expect(within(field()).getByText(/^Mar (9|10), 2567 BE$/)).toBeTruthy();
+ openSheet();
+ expect(
+ within(sheet()).getByRole('button', {
+ name: /^Created is after Mar (9|10), 2567 BE$/,
+ }),
+ ).toBeTruthy();
+ });
+
it("resolves the sheet's date-range and nested summaries through the catalog with the popover token's words", () => {
// The row's value resolves "date range" and "{n} filters" through
// `@astryx.powersearch.valueEditor.*` (ICU plural) so a locale can
diff --git a/packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx b/packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx
index ff91beb608..7cdbb1503a 100644
--- a/packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx
@@ -76,6 +76,7 @@ import {useAnnounce, type AnnounceFn} from '../hooks/useAnnounce';
import type {TranslatorFn} from '../i18n';
import {useListFormatter} from '../i18n/useListFormatter';
import {useLocale} from '../i18n/useLocale';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
import {SheetConfirmation} from '../internal/SheetConfirmation';
import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';
import {
@@ -968,6 +969,7 @@ export function PowerSearchBottomSheet({
const {NestedEditor} = editors;
const t = useComponentTranslator();
const locale = useLocale();
+ const calendar = useCalendarSystem(undefined, 'PowerSearch');
const formatList = useListFormatter();
const isInteractive = !isDisabled && !isReadOnly;
@@ -1524,13 +1526,14 @@ export function PowerSearchBottomSheet({
filter.value,
Number.MAX_SAFE_INTEGER,
locale,
+ calendar,
t,
formatList,
timezoneID,
);
return {label, value};
},
- [config, editors, formatList, locale, t, timezoneID],
+ [calendar, config, editors, formatList, locale, t, timezoneID],
);
const describeFilter = useCallback(
(filter: PowerSearchFilter): string => {
diff --git a/packages/core/src/PowerSearch/PowerSearchToken.tsx b/packages/core/src/PowerSearch/PowerSearchToken.tsx
index d7c4f6b8a1..a16f944040 100644
--- a/packages/core/src/PowerSearch/PowerSearchToken.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchToken.tsx
@@ -13,6 +13,7 @@ import React from 'react';
import * as stylex from '@stylexjs/stylex';
import {Token} from '../Token';
import {useLocale} from '../i18n/useLocale';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
import {fontWeightVars} from '../theme/tokens.stylex';
import {formatFilterValue} from './formatFilterValue';
import {resolveOperatorLabel} from './resolveOperatorLabel';
@@ -47,6 +48,7 @@ export function PowerSearchToken({
const config = useInternalConfig(configProp);
const t = useComponentTranslator();
const locale = useLocale();
+ const calendar = useCalendarSystem(undefined, 'PowerSearchToken');
const fieldLabel = field.label;
const resolvedOperatorLabel = resolveOperatorLabel(operator, t);
@@ -68,6 +70,7 @@ export function PowerSearchToken({
t,
locale,
timezoneID,
+ calendar,
);
const valueContent = valueStr ? (
diff --git a/packages/core/src/PowerSearch/formatFilterValue.test.ts b/packages/core/src/PowerSearch/formatFilterValue.test.ts
index 7cb10cfd68..c49cd7d068 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.test.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.test.ts
@@ -300,6 +300,115 @@ describe('formatFilterValue', () => {
}
});
+ describe.each([
+ {calendar: 'persian', locale: 'en', year: '1405'},
+ {calendar: 'persian', locale: 'fa', year: '۱۴۰۵'},
+ {calendar: 'hebrew', locale: 'en', year: '5787'},
+ {calendar: 'hebrew', locale: 'he', year: '5787'},
+ {calendar: 'buddhist', locale: 'en', year: '2569'},
+ {calendar: 'buddhist', locale: 'th', year: '2569'},
+ ] as const)(
+ 'absolute dates in $calendar under $locale',
+ ({calendar, locale, year}) => {
+ const instant = Date.parse('2026-10-30T12:00:00Z');
+ const unixSeconds = instant / 1000;
+
+ it('writes the editor summary in the calendar, with its time', () => {
+ const value = formatDateAbsolute(
+ unixSeconds,
+ locale,
+ 'UTC',
+ false,
+ calendar,
+ );
+ expect(value).toBe(
+ new Intl.DateTimeFormat(locale, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ timeZone: 'UTC',
+ calendar,
+ }).format(instant),
+ );
+ expect(value).toContain(year);
+ expect(value).not.toContain('2026');
+ });
+
+ it('writes the token value in the calendar', () => {
+ const value = formatDateAbsolute(
+ unixSeconds,
+ locale,
+ 'UTC',
+ true,
+ calendar,
+ );
+ expect(value).toBe(
+ new Intl.DateTimeFormat(locale, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC',
+ calendar,
+ }).format(instant),
+ );
+ expect(value).toContain(year);
+ });
+
+ it('passes the calendar through formatFilterValue', () => {
+ expect(
+ formatFilterValue(
+ {} as never,
+ {type: 'date_absolute'},
+ {type: 'date_absolute', unixSeconds},
+ 60,
+ t,
+ locale,
+ 'UTC',
+ calendar,
+ ),
+ ).toBe(
+ formatDateAbsolute(unixSeconds, locale, 'UTC', true, calendar),
+ );
+ });
+ },
+ );
+
+ it('defaults absolute dates to the Gregorian calendar', () => {
+ const unixSeconds = Date.parse('2026-10-30T12:00:00Z') / 1000;
+ expect(formatDateAbsolute(unixSeconds, 'fa', 'UTC')).toBe(
+ formatDateAbsolute(unixSeconds, 'fa', 'UTC', true, 'gregory'),
+ );
+ expect(formatDateAbsolute(unixSeconds, 'fa', 'UTC', false)).toBe(
+ formatDateAbsolute(unixSeconds, 'fa', 'UTC', false, 'gregory'),
+ );
+ expect(
+ fmt(
+ {type: 'date_absolute'},
+ {type: 'date_absolute', unixSeconds},
+ 60,
+ 'UTC',
+ ),
+ ).toContain('2026');
+ });
+
+ it('keeps time and relative values unchanged in another calendar', () => {
+ const inCalendar = (value: FilterValue) =>
+ formatFilterValue(
+ {} as never,
+ {type: value.type} as OperatorValue,
+ value,
+ 20,
+ t,
+ 'fa',
+ 'UTC',
+ 'persian',
+ );
+ expect(inCalendar({type: 'time', value: '14:30'})).toBe('14:30');
+ expect(inCalendar({type: 'date_relative', value: '7d'})).toBe('7d');
+ });
+
it('formats an absolute date and truncates to maxLength', () => {
const full = fmt(
{type: 'date_absolute'},
diff --git a/packages/core/src/PowerSearch/formatFilterValue.ts b/packages/core/src/PowerSearch/formatFilterValue.ts
index 5694e8c62f..b1a5a7929d 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.ts
@@ -2,7 +2,7 @@
/**
* @file formatFilterValue.ts
- * @input OperatorValue, FilterValue, config
+ * @input OperatorValue, FilterValue, config, locale, time zone, calendar
* @output Formatted display string for a filter value
* @position Pure utility; consumed by PowerSearch token rendering
*
@@ -13,6 +13,10 @@
import type {OperatorValue, FilterValue, EnumItem} from './types';
import type {InternalConfig} from './useInternalConfig';
import type {Locale, TranslatorFn} from '../i18n';
+import {
+ formatCalendarInstant,
+ type CalendarSystem,
+} from '../utils/calendarSystem';
import {truncateCharacters} from '../utils/characters';
import {registerEnglishFallback} from '../i18n/englishFallback';
import english from '../i18n/generated-english/PowerSearch/formatFilterValue.generated';
@@ -67,25 +71,24 @@ export function formatDateAbsolute(
locale: Locale,
timezoneID: string | undefined,
isDateOnly = true,
+ calendar: CalendarSystem = 'gregory',
): string {
const options: Intl.DateTimeFormatOptions = isDateOnly
- ? {
- year: 'numeric',
- month: 'short',
- day: 'numeric',
- timeZone: resolveDateZone(timezoneID, true),
- calendar: 'gregory',
- }
+ ? {year: 'numeric', month: 'short', day: 'numeric'}
: {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
- timeZone: resolveDateZone(timezoneID, false),
- calendar: 'gregory',
};
- return new Intl.DateTimeFormat(locale, options).format(unixSeconds * 1000);
+ return formatCalendarInstant(
+ calendar,
+ new Date(unixSeconds * 1000),
+ options,
+ locale,
+ resolveDateZone(timezoneID, isDateOnly),
+ );
}
function formatRelativeDate(value: string): string {
@@ -100,6 +103,11 @@ function formatDateRange(
return t('@astryx.powersearch.valueEditor.dateRange');
}
+/**
+ * The display text of a filter value. A `date_absolute` value is written in
+ * `calendar`, which defaults to Gregorian; PowerSearch passes the calendar that
+ * its provider resolves.
+ */
export function formatFilterValue(
_config: InternalConfig,
operatorValue: OperatorValue,
@@ -108,6 +116,7 @@ export function formatFilterValue(
t: TranslatorFn,
locale: Locale,
timezoneID?: string,
+ calendar: CalendarSystem = 'gregory',
): string {
switch (filterValue.type) {
case 'empty':
@@ -210,6 +219,7 @@ export function formatFilterValue(
timezoneID,
operatorValue.type !== 'date_absolute' ||
operatorValue.isDateOnly !== false,
+ calendar,
),
maxLength,
);
diff --git a/packages/core/src/PowerSearch/formatTokenValue.ts b/packages/core/src/PowerSearch/formatTokenValue.ts
index 9b4cad2c3c..96e4450678 100644
--- a/packages/core/src/PowerSearch/formatTokenValue.ts
+++ b/packages/core/src/PowerSearch/formatTokenValue.ts
@@ -3,7 +3,8 @@
/**
* @fileoverview The text a PowerSearch filter token shows for a value.
*
- * @input `OperatorValue`, `FilterValue`, a width budget, and the locale.
+ * @input `OperatorValue`, `FilterValue`, a width budget, the locale, and the
+ * calendar.
* @output `formatTokenValueText` — one string, or null for an empty value.
* @position Shared by the token itself (`PowerSearch.tsx`) and the sheet
* presentation's Filters rows and removal announcement
@@ -13,6 +14,7 @@
import type {OperatorValue, FilterValue, EnumItem} from './types';
import type {Locale, TranslatorFn} from '../i18n';
+import type {CalendarSystem} from '../utils/calendarSystem';
import {truncateCharacters} from '../utils/characters';
import {formatDateAbsolute, formatSharedNumber} from './formatFilterValue';
import {registerEnglishFallback} from '../i18n/englishFallback';
@@ -103,6 +105,8 @@ function formatListText(
* the sheet presentation's Filters rows and its removal announcement — can
* use the same words and the same zone handling. `maxLength` is the token's
* width budget; pass `Number.MAX_SAFE_INTEGER` for the untruncated text.
+ * A `date_absolute` value is written in `calendar`, the calendar that the
+ * provider resolves.
* With `t`, the list, date-range and nested summaries resolve through the
* catalog (`@astryx.powersearch.valueEditor.*`); without it they are the
* token's own literals. With `formatList` (the provider's list formatter),
@@ -114,6 +118,7 @@ export function formatTokenValueText(
filterValue: FilterValue,
maxLength: number,
locale: Locale,
+ calendar: CalendarSystem,
t?: TranslatorFn,
formatList?: ListFormatFn,
timezoneID?: string,
@@ -182,6 +187,7 @@ export function formatTokenValueText(
timezoneID,
operatorValue.type !== 'date_absolute' ||
operatorValue.isDateOnly !== false,
+ calendar,
),
maxLength,
);
diff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjs
index 2f13f18f4d..5b7da2c98a 100644
--- a/packages/core/src/Timestamp/Timestamp.doc.mjs
+++ b/packages/core/src/Timestamp/Timestamp.doc.mjs
@@ -28,7 +28,7 @@ export const docs = {
name: 'format',
type: "'relative' | 'relative_short' | 'auto' | 'date' | 'date_long' | 'date_weekday' | 'date_time' | 'time' | 'system_date' | 'system_date_time' | 'system_time' | 'unix_seconds'",
description:
- "Display format. 'relative' uses the locale's native long relative-time wording ('2 hours ago' in English), 'relative_short' uses its narrow pattern ('2h ago' in English) for compact surfaces, 'date' shows 'Mar 21, 2025', 'date_long' shows 'March 21, 2025', 'date_weekday' shows 'Wed, Mar 21, 2025', 'date_time' shows 'Mar 21, 2025, 2:51 PM', 'time' shows '2:51 PM', 'system_*' variants use ISO-style formatting, 'unix_seconds' shows the Unix time in whole seconds since the epoch (an absolute, zone-independent value), 'auto' switches from relative to date_time based on recency. Absolute formats never read the current time. 'relative', 'relative_short' and 'auto' read it on the client only: a server render or static prerender shows the full date and time in UTC, labelled, and the client switches to the format's normal output after hydration.",
+ "Display format. 'relative' uses the locale's native long relative-time wording ('2 hours ago' in English), 'relative_short' uses its narrow pattern ('2h ago' in English) for compact surfaces, 'date' shows 'Mar 21, 2025', 'date_long' shows 'March 21, 2025', 'date_weekday' shows 'Wed, Mar 21, 2025', 'date_time' shows 'Mar 21, 2025, 2:51 PM', 'time' shows '2:51 PM', 'system_*' variants use ISO-style formatting, 'unix_seconds' shows the Unix time in whole seconds since the epoch (an absolute, zone-independent value), 'auto' switches from relative to date_time based on recency. Absolute formats never read the current time. 'relative', 'relative_short' and 'auto' read it on the client only: a server render or static prerender shows the full date and time in UTC, labelled, and the client switches to the format's normal output after hydration. Date-bearing formats ('date', 'date_long', 'date_weekday', 'date_time', and the full date in the hover card and the accessible name) use the InternationalizationProvider calendar, such as calendar=\"persian\"; 'time', the relative formats, 'system_*', and 'unix_seconds' do not change.",
default: "'auto'",
},
{
@@ -124,7 +124,7 @@ export const docs = {
export const docsZh = {
propDescriptions: {
value: '\u8981\u663e\u793a\u7684\u65e5\u671f/\u65f6\u95f4\u3002\u63a5\u53d7 Unix \u65f6\u95f4\u6233\uff08\u79d2\uff09\u6216 ISO 8601 \u5b57\u7b26\u4e32\u3002',
- format: "\u663e\u793a\u683c\u5f0f\u3002'relative' \u663e\u793a '2\u5c0f\u65f6\u524d'\uff0c'date' \u663e\u793a\u65e5\u671f\uff0c'date_long' \u663e\u793a\u957f\u6708\u4efd\u65e5\u671f\uff0c'date_weekday' \u663e\u793a\u661f\u671f+\u65e5\u671f\uff0c'auto' \u6839\u636e\u65f6\u95f4\u8fdc\u8fd1\u81ea\u52a8\u5207\u6362\u3002",
+ format: "\u663e\u793a\u683c\u5f0f\u3002'relative' \u663e\u793a '2\u5c0f\u65f6\u524d'\uff0c'date' \u663e\u793a\u65e5\u671f\uff0c'date_long' \u663e\u793a\u957f\u6708\u4efd\u65e5\u671f\uff0c'date_weekday' \u663e\u793a\u661f\u671f+\u65e5\u671f\uff0c'auto' \u6839\u636e\u65f6\u95f4\u8fdc\u8fd1\u81ea\u52a8\u5207\u6362\u3002\u5e26\u65e5\u671f\u7684\u683c\u5f0f\uff08'date'\u3001'date_long'\u3001'date_weekday'\u3001'date_time'\uff0c\u4ee5\u53ca\u60ac\u505c\u5361\u7247\u548c\u65e0\u969c\u788d\u540d\u79f0\u4e2d\u7684\u5b8c\u6574\u65e5\u671f\uff09\u4f7f\u7528 InternationalizationProvider \u7684\u5386\u6cd5\uff08\u5982 calendar=\"persian\"\uff09\uff1b'time'\u3001\u76f8\u5bf9\u683c\u5f0f\u3001'system_*' \u548c 'unix_seconds' \u4e0d\u53d8\u3002",
autoThreshold: "auto \u683c\u5f0f\u4ece\u76f8\u5bf9\u65f6\u95f4\u5207\u6362\u5230 date_time \u7684\u9608\u503c\u79d2\u6570\u3002",
hasTooltip: '\u60ac\u505c\u65f6\u662f\u5426\u663e\u793a\u5305\u542b\u5b8c\u6574\u65e5\u671f/\u65f6\u95f4\u7684\u53ef\u590d\u5236\u60ac\u505c\u5361\u7247\uff08\u76f8\u5bf9\u65f6\u95f4\u6a21\u5f0f\uff0c\u6216\u914d\u7f6e tooltipEntries \u7684\u4efb\u610f\u683c\u5f0f\uff09\u3002',
tooltipEntries:
@@ -186,7 +186,7 @@ export const docsDense = {
},
propDescriptions: {
value: 'date/time as unix seconds or ISO string',
- format: "display mode: 'relative' (locale-native long wording), 'relative_short' (locale-native narrow wording), 'auto', 'date', 'date_long', 'date_weekday', 'date_time', 'time', 'system_date', 'system_date_time', 'system_time', 'unix_seconds'",
+ format: "display mode: 'relative' (locale-native long wording), 'relative_short' (locale-native narrow wording), 'auto', 'date', 'date_long', 'date_weekday', 'date_time', 'time', 'system_date', 'system_date_time', 'system_time', 'unix_seconds'; date-bearing formats use the provider calendar, system_* and time do not",
autoThreshold: 'seconds threshold for auto relative\u2192date_time switch',
hasTooltip: 'show copyable full-time hover card on hover (relative mode, or any format with tooltipEntries)',
tooltipEntries:
diff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsx
index 51ae76ab4c..3eae185125 100644
--- a/packages/core/src/Timestamp/Timestamp.test.tsx
+++ b/packages/core/src/Timestamp/Timestamp.test.tsx
@@ -1,5 +1,6 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+import 'temporal-polyfill/full/global';
import {
describe,
it,
@@ -7,9 +8,18 @@ import {
vi,
beforeAll,
beforeEach,
+ afterAll,
afterEach,
+ onTestFinished,
} from 'vitest';
-import {render, screen, act, waitFor, fireEvent} from '@testing-library/react';
+import {
+ render,
+ screen,
+ act,
+ waitFor,
+ fireEvent,
+ within,
+} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Profiler} from 'react';
import {hydrateRoot, type Root} from 'react-dom/client';
@@ -19,6 +29,9 @@ import {formatInstant} from './formatInstant';
import {formatTooltipLines} from './tooltipEntries';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {InternationalizationProvider} from '../i18n';
+import type {CalendarSystem} from '../utils/calendarSystem';
+import {withChineseTemporalAheadOfIntl} from '../__tests__/temporalAheadOfIntl';
+import {__resetDevWarnings} from '../utils/devWarning';
async function openTimestampHoverCard(): Promise<HTMLElement> {
const timestamp = document.querySelector('time');
@@ -1659,3 +1672,313 @@ describe('Timestamp server rendering', () => {
}
});
});
+
+describe('Timestamp calendar systems', () => {
+ const INSTANT = new Date('2026-10-30T12:00:00Z');
+ const VALUE = INSTANT.toISOString();
+
+ // Independent option bags: the date-bearing formats as Intl spells them.
+ const DATE_OPTIONS = {
+ full: {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ second: '2-digit',
+ timeZoneName: 'short',
+ },
+ date: {year: 'numeric', month: 'short', day: 'numeric'},
+ date_long: {year: 'numeric', month: 'long', day: 'numeric'},
+ date_weekday: {
+ weekday: 'short',
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ },
+ date_time: {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ },
+ } as const satisfies Record<string, Intl.DateTimeFormatOptions>;
+ const DATE_FORMATS = Object.keys(
+ DATE_OPTIONS,
+ ) as (keyof typeof DATE_OPTIONS)[];
+ const CALENDAR_LOCALES = [
+ {calendar: 'persian', locale: 'en', year: '1405'},
+ {calendar: 'persian', locale: 'fa', year: '۱۴۰۵'},
+ {calendar: 'hebrew', locale: 'en', year: '5787'},
+ {calendar: 'hebrew', locale: 'he', year: '5787'},
+ {calendar: 'buddhist', locale: 'en', year: '2569'},
+ {calendar: 'buddhist', locale: 'th', year: '2569'},
+ ] as const;
+
+ afterEach(() => {
+ __resetDevWarnings();
+ vi.restoreAllMocks();
+ });
+
+ describe.each(CALENDAR_LOCALES)(
+ 'formatInstant in $calendar under $locale',
+ ({calendar, locale, year}) => {
+ it.each(DATE_FORMATS)('writes %s in the calendar', format => {
+ const value = formatInstant(INSTANT, format, locale, {
+ timeZone: 'UTC',
+ calendar,
+ });
+ expect(value).toBe(
+ new Intl.DateTimeFormat(locale, {
+ ...DATE_OPTIONS[format],
+ timeZone: 'UTC',
+ calendar,
+ }).format(INSTANT),
+ );
+ expect(value).toContain(year);
+ expect(value).not.toContain('2026');
+ });
+
+ it.each([
+ 'time',
+ 'system_date',
+ 'system_date_time',
+ 'system_time',
+ 'unix_seconds',
+ ] as const)('keeps %s unchanged', format => {
+ expect(
+ formatInstant(INSTANT, format, locale, {timeZone: 'UTC', calendar}),
+ ).toBe(formatInstant(INSTANT, format, locale, {timeZone: 'UTC'}));
+ });
+ },
+ );
+
+ it.each(DATE_FORMATS)('defaults %s to the Gregorian calendar', format => {
+ expect(formatInstant(INSTANT, format, 'fa', {timeZone: 'UTC'})).toBe(
+ formatInstant(INSTANT, format, 'fa', {
+ timeZone: 'UTC',
+ calendar: 'gregory',
+ }),
+ );
+ expect(formatInstant(INSTANT, format, 'en', {timeZone: 'UTC'})).toContain(
+ '2026',
+ );
+ });
+
+ it('keeps the system formats Gregorian ISO in every calendar', () => {
+ expect(
+ formatInstant(INSTANT, 'system_date_time', 'fa', {
+ timeZone: 'UTC',
+ calendar: 'persian',
+ }),
+ ).toBe('2026-10-30 12:00:00');
+ });
+
+ function renderTimestamp(
+ provider: {locale: string; calendar?: CalendarSystem},
+ format: 'date_long' | 'date_time' | 'system_date' | 'relative',
+ ) {
+ return render(
+ <InternationalizationProvider {...provider}>
+ <Timestamp
+ value={VALUE}
+ format={format}
+ hasTooltip={false}
+ data-testid="ts"
+ />
+ </InternationalizationProvider>,
+ );
+ }
+
+ it.each(CALENDAR_LOCALES)(
+ 'renders date_long in the provider calendar $calendar under $locale',
+ ({calendar, locale, year}) => {
+ renderTimestamp({locale, calendar}, 'date_long');
+ const text = screen.getByTestId('ts').textContent;
+ expect(text).toBe(
+ formatInstant(INSTANT, 'date_long', locale, {calendar}),
+ );
+ expect(text).toContain(year);
+ },
+ );
+
+ it('keeps the time of day of date_time in the provider calendar', () => {
+ renderTimestamp({locale: 'en', calendar: 'persian'}, 'date_time');
+ const text = screen.getByTestId('ts').textContent ?? '';
+ expect(text).toBe(
+ formatInstant(INSTANT, 'date_time', 'en', {calendar: 'persian'}),
+ );
+ expect(text).toContain('Aban');
+ expect(text).toMatch(/\d:\d\d/);
+ });
+
+ it('keeps system_date Gregorian ISO under a provider calendar', () => {
+ renderTimestamp({locale: 'fa', calendar: 'persian'}, 'system_date');
+ expect(screen.getByTestId('ts').textContent).toBe(
+ formatInstant(INSTANT, 'system_date', 'fa'),
+ );
+ expect(screen.getByTestId('ts').textContent).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ });
+
+ it('names relative output with the full date in the provider calendar', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(INSTANT.getTime() + 2 * 3600 * 1000));
+ try {
+ renderTimestamp({locale: 'en', calendar: 'hebrew'}, 'relative');
+ const name = screen.getByTestId('ts').getAttribute('aria-label') ?? '';
+ expect(name).toBe(
+ formatInstant(INSTANT, 'full', 'en', {
+ calendar: 'hebrew',
+ timeZoneNameStyle: 'long',
+ }),
+ );
+ expect(name).toContain('5787');
+ expect(screen.getByTestId('ts').textContent).toBe('2 hours ago');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps Gregorian dates for a -u-ca- keyword in the provider locale', () => {
+ renderTimestamp({locale: 'th-TH-u-ca-buddhist'}, 'date_long');
+ const ts = screen.getByTestId('ts');
+ expect(ts).toHaveTextContent('2026');
+ expect(ts).not.toHaveTextContent('2569');
+ });
+
+ it('keeps Gregorian dates when the locale names no calendar', () => {
+ renderTimestamp({locale: 'fa-IR'}, 'date_long');
+ expect(screen.getByTestId('ts').textContent).toBe(
+ formatInstant(INSTANT, 'date_long', 'fa-IR'),
+ );
+ });
+
+ it('writes tooltip rows in the provider calendar', async () => {
+ await import('./TimestampHoverCard');
+ const originalShowPopover = HTMLElement.prototype.showPopover;
+ HTMLElement.prototype.showPopover = vi.fn();
+ onTestFinished(() => {
+ HTMLElement.prototype.showPopover = originalShowPopover;
+ });
+ render(
+ <InternationalizationProvider locale="en" calendar="persian">
+ <Timestamp
+ value={VALUE}
+ format="date"
+ tooltipEntries={[
+ {timezoneID: 'UTC', label: 'UTC'},
+ {timezoneID: 'UTC', format: 'system_date_time', label: 'ISO'},
+ ]}
+ data-testid="ts"
+ />
+ </InternationalizationProvider>,
+ );
+ const card = await openTimestampHoverCard();
+ expect(
+ within(card).getByText(
+ formatInstant(INSTANT, 'full', 'en', {
+ timeZone: 'UTC',
+ calendar: 'persian',
+ }),
+ ),
+ ).toBeInTheDocument();
+ expect(within(card).getByText('2026-10-30 12:00:00')).toBeInTheDocument();
+ });
+
+ describe('without Temporal', () => {
+ const globals = globalThis as {Temporal?: unknown};
+ let savedTemporal: unknown;
+
+ beforeAll(() => {
+ savedTemporal = globals.Temporal;
+ delete globals.Temporal;
+ });
+
+ afterAll(() => {
+ globals.Temporal = savedTemporal;
+ });
+
+ it('shows Gregorian dates for a calendar that needs Temporal', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ renderTimestamp({locale: 'en', calendar: 'persian'}, 'date_long');
+ expect(screen.getByTestId('ts').textContent).toBe(
+ formatInstant(INSTANT, 'date_long', 'en'),
+ );
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('needs a Temporal that supports it'),
+ );
+ });
+
+ it('still shows the buddhist calendar, which needs no Temporal', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ renderTimestamp({locale: 'en', calendar: 'buddhist'}, 'date_long');
+ expect(screen.getByTestId('ts')).toHaveTextContent('2569');
+ expect(warn).not.toHaveBeenCalled();
+ });
+ });
+
+ it.each(['date', 'date_long', 'date_weekday', 'date_time', 'full'] as const)(
+ 'writes %s in the `chinese` calendar on the day that Calendar shows',
+ format => {
+ const value = withChineseTemporalAheadOfIntl(() =>
+ formatInstant(new Date('2027-02-06T12:00:00Z'), format, 'en', {
+ timeZone: 'UTC',
+ calendar: 'chinese',
+ }),
+ );
+ // Intl alone names the 30th day of the Twelfth Month of 2026.
+ expect(value).toMatch(/\b(Mo1|First Month) 1, 2027/);
+ },
+ );
+
+ it.each(['date_time', 'full'] as const)(
+ 'writes %s in `iso8601` as in `gregory`',
+ format => {
+ expect(
+ formatInstant(INSTANT, format, 'en', {
+ timeZone: 'UTC',
+ calendar: 'iso8601',
+ }),
+ ).toBe(formatInstant(INSTANT, format, 'en', {timeZone: 'UTC'}));
+ },
+ );
+
+ it('hydrates a clock format rendered on a server without Temporal', () => {
+ const value = Date.now() / 1000 - 7200;
+ const element = (
+ <InternationalizationProvider locale="en" calendar="persian">
+ <Timestamp value={value} format="relative" hasTooltip={false} />
+ </InternationalizationProvider>
+ );
+ const globals = globalThis as {Temporal?: unknown};
+ const savedTemporal = globals.Temporal;
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const host = document.createElement('div');
+ delete globals.Temporal;
+ try {
+ host.innerHTML = renderToString(element);
+ } finally {
+ globals.Temporal = savedTemporal;
+ }
+ document.body.appendChild(host);
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const recovered: unknown[] = [];
+ let root: Root | undefined;
+ try {
+ act(() => {
+ root = hydrateRoot(host, element, {
+ onRecoverableError: error => recovered.push(error),
+ });
+ });
+ expect(host.textContent).toBe('2 hours ago');
+ expect(recovered).toEqual([]);
+ expect(errors).not.toHaveBeenCalled();
+ } finally {
+ errors.mockRestore();
+ warn.mockRestore();
+ act(() => root?.unmount());
+ host.remove();
+ }
+ });
+});
diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsx
index ab80ca3ed7..e9fc6d9160 100644
--- a/packages/core/src/Timestamp/Timestamp.tsx
+++ b/packages/core/src/Timestamp/Timestamp.tsx
@@ -4,7 +4,7 @@
/**
* @file Timestamp.tsx
- * @input Uses React, Text, provider locale, and Timestamp formatters
+ * @input Uses React, Text, provider locale and calendar, and Timestamp formatters
* @output Exports Timestamp component and related types
* @position Core implementation; renders formatted timestamps
*
@@ -31,6 +31,7 @@ import type {TextType, TextSize, TextColor, TextWeight} from '../theme/types';
import {mergeProps} from '../utils';
import {useDevWarning} from '../hooks/useDevWarning';
import {useLocale} from '../i18n/useLocale';
+import {useCalendarSystem} from '../i18n/useCalendarSystem';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {formatInstant} from './formatInstant';
@@ -297,6 +298,7 @@ export function Timestamp({
}: TimestampProps) {
const t = useComponentTranslator();
const locale = useLocale();
+ const calendar = useCalendarSystem(undefined, 'Timestamp');
const timeRef = useRef<HTMLTimeElement>(null);
const mergedTimeRef = useMergedRefs(ref, timeRef);
// Only relative and auto formats depend on the current time. Absolute
@@ -358,12 +360,12 @@ export function Timestamp({
date,
effectiveFormat,
locale,
- // The pre-hydration placeholder is written in UTC, labelled, so
- // the server and the hydrating client produce the same text in
- // every time zone.
+ // The placeholder before hydration is Gregorian and in UTC, with
+ // its zone. The server and the client then write the same text,
+ // with or without Temporal.
isClockPending
? {timeZone: 'UTC', isTimezoneShown: true}
- : {isTimezoneShown},
+ : {isTimezoneShown, calendar},
)
: '';
@@ -372,10 +374,13 @@ export function Timestamp({
// out in full: abbreviations like "PST" or "GMT+2" are unexpanded
// abbreviations to a screen-reader user (WCAG 3.1.4).
const fullAbsoluteText = isValidDate
- ? formatInstant(date, 'full', locale)
+ ? formatInstant(date, 'full', locale, {calendar})
: '';
const ariaLabelText = isValidDate
- ? formatInstant(date, 'full', locale, {timeZoneNameStyle: 'long'})
+ ? formatInstant(date, 'full', locale, {
+ timeZoneNameStyle: 'long',
+ calendar,
+ })
: '';
// Syncs the relative time with an interval timer while the timestamp is live.
@@ -424,7 +429,7 @@ export function Timestamp({
const lines: ReadonlyArray<TimestampTooltipLine> =
entries === undefined
? [{value: fullAbsoluteText, isCopyable: true}]
- : formatTooltipLines(date, entries, locale);
+ : formatTooltipLines(date, entries, locale, calendar);
const timestampProps = mergeProps(
themeProps('timestamp', {format: effectiveFormat}),
diff --git a/packages/core/src/Timestamp/formatInstant.ts b/packages/core/src/Timestamp/formatInstant.ts
index 746bb5efd5..7760e2f744 100644
--- a/packages/core/src/Timestamp/formatInstant.ts
+++ b/packages/core/src/Timestamp/formatInstant.ts
@@ -2,7 +2,7 @@
/**
* @file formatInstant.ts
- * @input A Date, one absolute format name, and an optional time zone
+ * @input A Date, one absolute format name, an optional time zone and calendar
* @output That instant rendered as a string
* @position Leaf shared by Timestamp's visible text and each of its tooltip
* lines; owns every absolute format Timestamp can produce
@@ -30,6 +30,10 @@
*/
import {SHARED_DATE_FORMAT_OPTIONS, getWallClock} from '../utils/plainDate';
+import {
+ formatCalendarInstant,
+ type CalendarSystem,
+} from '../utils/calendarSystem';
import type {Locale} from '../i18n/types';
import type {TimestampFormat} from './Timestamp';
@@ -80,6 +84,14 @@ export interface FormatInstantOptions {
* @default 'short'
*/
timeZoneNameStyle?: 'short' | 'long';
+ /**
+ * The calendar that date-bearing formats write the date in. Timestamp
+ * passes its resolved calendar. `time` has no date, and the `system_*`
+ * shapes and `unix_seconds` stay Gregorian ISO or calendar-neutral in every
+ * calendar.
+ * @default 'gregory'
+ */
+ calendar?: CalendarSystem;
}
// =============================================================================
@@ -139,6 +151,7 @@ export function formatInstant(
timeZone,
isTimezoneShown = false,
timeZoneNameStyle = 'short',
+ calendar = 'gregory',
}: FormatInstantOptions = {},
): string {
const zone = timeZone === undefined ? {} : {timeZone};
@@ -146,41 +159,49 @@ export function formatInstant(
switch (format) {
case 'full':
- return new Intl.DateTimeFormat(locale, {
- ...FULL_OPTIONS,
- timeZoneName: timeZoneNameStyle,
- ...zone,
- calendar: 'gregory',
- }).format(date);
+ return formatCalendarInstant(
+ calendar,
+ date,
+ {...FULL_OPTIONS, timeZoneName: timeZoneNameStyle},
+ locale,
+ timeZone,
+ );
case 'date':
- return new Intl.DateTimeFormat(locale, {
- ...SHARED_DATE_FORMAT_OPTIONS.date,
- ...zone,
- calendar: 'gregory',
- }).format(date);
+ return formatCalendarInstant(
+ calendar,
+ date,
+ SHARED_DATE_FORMAT_OPTIONS.date,
+ locale,
+ timeZone,
+ );
case 'date_long':
- return new Intl.DateTimeFormat(locale, {
- ...SHARED_DATE_FORMAT_OPTIONS.date_long,
- ...zone,
- calendar: 'gregory',
- }).format(date);
+ return formatCalendarInstant(
+ calendar,
+ date,
+ SHARED_DATE_FORMAT_OPTIONS.date_long,
+ locale,
+ timeZone,
+ );
case 'date_weekday':
- return new Intl.DateTimeFormat(locale, {
- ...SHARED_DATE_FORMAT_OPTIONS.date_weekday,
- ...zone,
- calendar: 'gregory',
- }).format(date);
+ return formatCalendarInstant(
+ calendar,
+ date,
+ SHARED_DATE_FORMAT_OPTIONS.date_weekday,
+ locale,
+ timeZone,
+ );
case 'date_time':
- return new Intl.DateTimeFormat(locale, {
- ...DATE_TIME_OPTIONS,
- ...zoneName,
- ...zone,
- calendar: 'gregory',
- }).format(date);
+ return formatCalendarInstant(
+ calendar,
+ date,
+ {...DATE_TIME_OPTIONS, ...zoneName},
+ locale,
+ timeZone,
+ );
case 'time':
return new Intl.DateTimeFormat(locale, {
diff --git a/packages/core/src/Timestamp/tooltipEntries.test.ts b/packages/core/src/Timestamp/tooltipEntries.test.ts
index 9d7e79424a..ecdcc5704b 100644
--- a/packages/core/src/Timestamp/tooltipEntries.test.ts
+++ b/packages/core/src/Timestamp/tooltipEntries.test.ts
@@ -564,3 +564,54 @@ describe('formatTooltipLines', () => {
expect(lines[0].value).toBe('2026-02-20 02:00:00');
});
});
+
+describe('formatTooltipLines calendar', () => {
+ const CALENDAR_INSTANT = new Date('2026-10-30T12:00:00Z');
+
+ it.each([
+ {calendar: 'persian', locale: 'en', year: '1405'},
+ {calendar: 'persian', locale: 'fa', year: '۱۴۰۵'},
+ {calendar: 'hebrew', locale: 'en', year: '5787'},
+ {calendar: 'hebrew', locale: 'he', year: '5787'},
+ {calendar: 'buddhist', locale: 'en', year: '2569'},
+ {calendar: 'buddhist', locale: 'th', year: '2569'},
+ ] as const)(
+ 'writes date rows in $calendar under $locale and keeps system rows ISO',
+ ({calendar, locale, year}) => {
+ const [dateLine, systemLine] = formatTooltipLinesForLocale(
+ CALENDAR_INSTANT,
+ [
+ {timezoneID: 'UTC', format: 'date_long'},
+ {timezoneID: 'UTC', format: 'system_date_time'},
+ ],
+ locale,
+ calendar,
+ );
+ expect(dateLine.value).toBe(
+ new Intl.DateTimeFormat(locale, {
+ ...SHARED_DATE_FORMAT_OPTIONS.date_long,
+ timeZone: 'UTC',
+ calendar,
+ }).format(CALENDAR_INSTANT),
+ );
+ expect(dateLine.value).toContain(year);
+ expect(systemLine.value).toBe('2026-10-30 12:00:00');
+ },
+ );
+
+ it('defaults to the Gregorian calendar', () => {
+ const [line] = formatTooltipLinesForLocale(
+ CALENDAR_INSTANT,
+ [{timezoneID: 'UTC', format: 'date_long'}],
+ 'fa',
+ );
+ expect(line.value).toBe(
+ formatTooltipLinesForLocale(
+ CALENDAR_INSTANT,
+ [{timezoneID: 'UTC', format: 'date_long'}],
+ 'fa',
+ 'gregory',
+ )[0].value,
+ );
+ });
+});
diff --git a/packages/core/src/Timestamp/tooltipEntries.ts b/packages/core/src/Timestamp/tooltipEntries.ts
index 36ce3dcfc3..d891390f4c 100644
--- a/packages/core/src/Timestamp/tooltipEntries.ts
+++ b/packages/core/src/Timestamp/tooltipEntries.ts
@@ -2,7 +2,7 @@
/**
* @file tooltipEntries.ts
- * @input A Date and the consumer's tooltip entry list
+ * @input A Date, the consumer's tooltip entry list, a locale and a calendar
* @output Pure formatting of one tooltip line per entry, plus the entry types
* @position Leaf module; owns which zone each tooltip line names and whether
* it needs a zone abbreviation, then defers to formatInstant to render it
@@ -25,6 +25,7 @@ import {devWarn} from '../utils/devWarning';
import {formatInstant} from './formatInstant';
import type {InstantFormat} from './formatInstant';
import type {Locale} from '../i18n/types';
+import type {CalendarSystem} from '../utils/calendarSystem';
// =============================================================================
// Types
@@ -197,15 +198,17 @@ function shouldShowZoneName(
}
/**
- * Renders one tooltip line per entry, in the order given.
+ * Renders one tooltip line per entry, in the order given, with dates in
+ * `calendar`.
*
* Pure: the same `date` and `entries` always produce the same lines for a given
- * host zone and locale.
+ * host zone, locale, and calendar.
*/
export function formatTooltipLines(
date: Date,
entries: ReadonlyArray<TimestampTooltipEntry>,
locale: Locale,
+ calendar: CalendarSystem = 'gregory',
): ReadonlyArray<TimestampTooltipLine> {
const resolved = entries.map(entry => resolveTimezoneID(entry.timezoneID));
const hasMultipleZones = new Set(resolved.map(zoneKey)).size > 1;
@@ -219,6 +222,7 @@ export function formatTooltipLines(
isCopyable: entry.isCopyable ?? false,
value: formatInstant(date, format, locale, {
timeZone,
+ calendar,
isTimezoneShown: shouldShowZoneName(
format,
hasMultipleZones,
diff --git a/packages/core/src/__tests__/temporalAheadOfIntl.ts b/packages/core/src/__tests__/temporalAheadOfIntl.ts
new file mode 100644
index 0000000000..48339bf403
--- /dev/null
+++ b/packages/core/src/__tests__/temporalAheadOfIntl.ts
@@ -0,0 +1,68 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file temporalAheadOfIntl.ts
+ * @input The global Temporal, which a test sets with the full polyfill
+ * @output withChineseTemporalAheadOfIntl — runs a callback with a Temporal
+ * whose `chinese` calendar starts a month one day before Intl does
+ * @position Shared test helper for date labels where Intl and Temporal
+ * disagree on a month start of the Chinese or Dangi calendar
+ */
+
+interface TestPlainDate {
+ readonly year: number;
+ readonly month: number;
+ readonly day: number;
+ readonly daysInMonth: number;
+ with(fields: {day: number}): TestPlainDate;
+ add(duration: object): TestPlainDate;
+ subtract(duration: object): TestPlainDate;
+ withCalendar(calendar: string): TestPlainDate;
+}
+
+type TestPlainDateConstructor = new (
+ isoYear: number,
+ isoMonth: number,
+ isoDay: number,
+ calendar: string,
+) => TestPlainDate;
+
+/**
+ * Runs `run` with a Temporal whose `chinese` calendar is one day ahead of
+ * Intl's, as native Temporal is at some month starts. Intl calls 2027-02-06
+ * the 30th day of the Twelfth Month; this Temporal calls it the first day of
+ * the first month of the 2027 `chinese` year.
+ */
+export function withChineseTemporalAheadOfIntl<T>(run: () => T): T {
+ const globals = globalThis as unknown as {
+ Temporal: {PlainDate: TestPlainDateConstructor};
+ };
+ const real = globals.Temporal;
+ const shift = (inner: TestPlainDate): TestPlainDate => ({
+ year: inner.year,
+ month: inner.month,
+ day: inner.day,
+ daysInMonth: inner.daysInMonth,
+ with: fields => shift(inner.with(fields)),
+ add: duration => shift(inner.add(duration)),
+ subtract: duration => shift(inner.subtract(duration)),
+ withCalendar: calendar => inner.withCalendar(calendar).subtract({days: 1}),
+ });
+ function PlainDate(y: number, m: number, d: number, calendar: string) {
+ return calendar === 'chinese'
+ ? shift(
+ new real.PlainDate(y, m, d, 'iso8601')
+ .add({days: 1})
+ .withCalendar('chinese'),
+ )
+ : new real.PlainDate(y, m, d, calendar);
+ }
+ globals.Temporal = {
+ PlainDate: PlainDate as unknown as TestPlainDateConstructor,
+ };
+ try {
+ return run();
+ } finally {
+ globals.Temporal = real;
+ }
+}
diff --git a/packages/core/src/i18n/InternationalizationProvider.doc.mjs b/packages/core/src/i18n/InternationalizationProvider.doc.mjs
index e66f4afd40..0c90ff4239 100644
--- a/packages/core/src/i18n/InternationalizationProvider.doc.mjs
+++ b/packages/core/src/i18n/InternationalizationProvider.doc.mjs
@@ -53,7 +53,7 @@ export const docs = {
{
guidance: true,
description:
- 'Set `calendar` to show `Calendar` in another calendar system; `DateInput`, `DateRangeInput`, and `DateTimeInput` show Gregorian dates. A locale never selects the calendar: `fa-IR` shows Gregorian dates until you set `calendar="persian"`, and a `-u-ca-` keyword in `locale`, as in `th-TH-u-ca-buddhist`, keeps Gregorian dates too. Date values stay Gregorian ISO strings.',
+ 'Set `calendar` to show `Calendar` in another calendar system and write Timestamp and PowerSearch dates in it; `DateInput`, `DateRangeInput`, and `DateTimeInput` show Gregorian dates. A locale never selects the calendar: `fa-IR` shows Gregorian dates until you set `calendar="persian"`, and a `-u-ca-` keyword in `locale`, as in `th-TH-u-ca-buddhist`, keeps Gregorian dates too. Date values stay Gregorian ISO strings.',
},
{
guidance: false,
@@ -96,7 +96,7 @@ export const docs = {
type: "'gregory' | 'iso8601' | 'buddhist' | 'roc' | 'japanese' | 'persian' | 'indian' | 'hebrew' | 'chinese' | 'dangi' | 'coptic' | 'ethiopic' | 'ethioaa' | 'islamic-civil' | 'islamic-tbla' | 'islamic-umalqura'",
required: false,
description:
- "Calendar system that `Calendar` in the subtree shows, such as 'persian', 'hebrew', or 'buddhist'. `DateInput`, `DateRangeInput`, and `DateTimeInput` show Gregorian dates. When omitted, the calendar is Gregorian: a locale never selects it, neither by its default calendar nor by a `-u-ca-` keyword. A component's own `calendar` prop takes precedence. Values stay Gregorian ISO dates. Calendars other than gregory, iso8601, buddhist, roc, and japanese need `Temporal`; the context keeps the requested calendar, and where the runtime lacks `Temporal`, `Calendar` shows Gregorian dates and warns in development. Load a polyfill such as `temporal-polyfill/full/global` on the server and in the browser.",
+ "Calendar system of the subtree, such as 'persian', 'hebrew', or 'buddhist'. `Calendar` shows it, and Timestamp and PowerSearch write their dates in it. `DateInput`, `DateRangeInput`, and `DateTimeInput` show Gregorian dates. When omitted, the calendar is Gregorian: a locale never selects it, neither by its default calendar nor by a `-u-ca-` keyword. A component's own `calendar` prop takes precedence. Values stay Gregorian ISO dates. Calendars other than gregory, iso8601, buddhist, roc, and japanese need `Temporal`; the context keeps the requested calendar, and where the runtime lacks `Temporal`, these components show Gregorian dates and warn in development. Load a polyfill such as `temporal-polyfill/full/global` on the server and in the browser.",
},
{
name: 'children',
@@ -217,6 +217,6 @@ export const docsDense = {
overrides:
'sparse per-locale key overrides applied on top of shipped defaults',
calendar:
- 'calendar system for Calendar; date inputs stay Gregorian (default: gregory; a -u-ca- keyword in locale does not select it); values stay Gregorian ISO; non-Gregorian-aligned calendars need Temporal',
+ 'calendar system for Calendar, Timestamp, and PowerSearch dates; date inputs stay Gregorian (default: gregory; a -u-ca- keyword in locale does not select it); values stay Gregorian ISO; non-Gregorian-aligned calendars need Temporal',
},
};
diff --git a/packages/core/src/i18n/InternationalizationProvider.tsx b/packages/core/src/i18n/InternationalizationProvider.tsx
index 503ae53c66..da10d0407e 100644
--- a/packages/core/src/i18n/InternationalizationProvider.tsx
+++ b/packages/core/src/i18n/InternationalizationProvider.tsx
@@ -105,14 +105,15 @@ export interface InternationalizationProviderProps {
*/
dir?: 'ltr' | 'rtl';
/**
- * The calendar system that `Calendar` in this subtree shows, such as
- * `'persian'` or `'hebrew'`. The date inputs show Gregorian dates. Values
- * stay Gregorian ISO dates. When omitted, the calendar is Gregorian: a locale
- * never selects it, neither by its default calendar nor by a `-u-ca-`
- * keyword. A component's own `calendar` prop takes precedence. Calendars
- * other than `gregory`, `iso8601`, `buddhist`, `roc`, and `japanese` need
- * `Temporal`. The context keeps the requested calendar; where `Temporal` is
- * missing, `Calendar` shows Gregorian dates and warns once in development.
+ * The calendar system of this subtree, such as `'persian'` or `'hebrew'`.
+ * `Calendar` shows it, and Timestamp and PowerSearch write their dates in it.
+ * The date inputs show Gregorian dates. Values stay Gregorian ISO dates. When
+ * omitted, the calendar is Gregorian: a locale never selects it, neither by
+ * its default calendar nor by a `-u-ca-` keyword. A component's own
+ * `calendar` prop takes precedence. Calendars other than `gregory`,
+ * `iso8601`, `buddhist`, `roc`, and `japanese` need `Temporal`. The context
+ * keeps the requested calendar; where `Temporal` is missing, these components
+ * show Gregorian dates and warn once in development.
*
* @example
* ```
diff --git a/packages/core/src/utils/calendarSystem.test.ts b/packages/core/src/utils/calendarSystem.test.ts
index c361f2bdc4..3b91b88b05 100644
--- a/packages/core/src/utils/calendarSystem.test.ts
+++ b/packages/core/src/utils/calendarSystem.test.ts
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import 'temporal-polyfill/full/global';
-import {describe, expect, it} from 'vitest';
+import {afterEach, describe, expect, it} from 'vitest';
import {
CALENDAR_SYSTEMS,
type CalendarMonth,
@@ -14,6 +14,7 @@ import {
calendarShiftMonths,
calendarShiftYears,
formatCalendarDate,
+ formatCalendarInstant,
formatCalendarMonthLabel,
isCalendarSystemAvailable,
isGregorianAligned,
@@ -21,12 +22,15 @@ import {
} from './calendarSystem';
import {
DATE_FORMAT_WITH_WEEKDAY,
+ formatSharedDate,
type PlainDate,
plainDateAddDays,
+ plainDateFormat,
plainDateFromISO,
plainDateIsAfter,
plainDateToISO,
} from './plainDate';
+import {withChineseTemporalAheadOfIntl} from '../__tests__/temporalAheadOfIntl';
import type {ISODateString} from './dateTypes';
const iso = plainDateFromISO;
@@ -279,6 +283,85 @@ describe('calendar labels', () => {
});
});
+describe('labels where Intl and Temporal disagree', () => {
+ const day = iso('2027-02-06');
+ const noon = new Date('2027-02-06T12:00:00Z');
+ const longDate = {year: 'numeric', month: 'long', day: 'numeric'} as const;
+
+ it('names the Temporal day in plainDateFormat and formatSharedDate', () => {
+ withChineseTemporalAheadOfIntl(() => {
+ const options = {
+ month: 'long',
+ day: 'numeric',
+ calendar: 'chinese',
+ } as const;
+ expect(plainDateFormat(day, options, 'en')).toBe('First Month 1');
+ expect(formatSharedDate(day, 'date_long', 'en', 'chinese')).toMatch(
+ /^First Month 1, 2027/,
+ );
+ });
+ });
+
+ it('names the Temporal day of an instant and keeps its time', () => {
+ const value = withChineseTemporalAheadOfIntl(() =>
+ formatCalendarInstant(
+ 'chinese',
+ noon,
+ {...longDate, hour: 'numeric', minute: '2-digit'},
+ 'en',
+ 'UTC',
+ ),
+ );
+ expect(value).toMatch(/^First Month 1, 2027\(ding-wei\) at 12:00\sPM$/);
+ });
+});
+
+describe('iso8601 labels', () => {
+ const end = new Date('2027-02-06T12:00:00Z');
+ const longDate = {year: 'numeric', month: 'long', day: 'numeric'} as const;
+
+ it('writes dates and instants as gregory does', () => {
+ const day = iso('2027-02-06');
+ expect(formatSharedDate(day, 'date', 'en', 'iso8601')).toBe(
+ formatSharedDate(day, 'date', 'en'),
+ );
+ const dateTime = {...longDate, hour: 'numeric', minute: '2-digit'} as const;
+ expect(formatCalendarInstant('iso8601', end, dateTime, 'en', 'UTC')).toBe(
+ formatCalendarInstant('gregory', end, dateTime, 'en', 'UTC'),
+ );
+ });
+});
+
+describe('instants in the host zone', () => {
+ const originalTZ = process.env.TZ;
+ afterEach(() => {
+ if (originalTZ === undefined) {
+ delete process.env.TZ;
+ } else {
+ process.env.TZ = originalTZ;
+ }
+ });
+
+ it('follows a host zone change between calls', () => {
+ const instant = new Date('2026-10-30T20:00:00Z');
+ const options = {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ } as const;
+ process.env.TZ = 'UTC';
+ expect(formatCalendarInstant('persian', instant, options, 'en')).toMatch(
+ /^Aban 8, 1405 AP.* 8:00\sPM$/,
+ );
+ process.env.TZ = 'Asia/Tokyo';
+ expect(formatCalendarInstant('persian', instant, options, 'en')).toMatch(
+ /^Aban 9, 1405 AP.* 5:00\sAM$/,
+ );
+ });
+});
+
describe('dates from calendar fields', () => {
const toISO = (pd: PlainDate | null) =>
pd == null ? null : plainDateToISO(pd);
diff --git a/packages/core/src/utils/calendarSystem.ts b/packages/core/src/utils/calendarSystem.ts
index db163a03e5..77d287f644 100644
--- a/packages/core/src/utils/calendarSystem.ts
+++ b/packages/core/src/utils/calendarSystem.ts
@@ -14,13 +14,15 @@
import type {Locale} from '../i18n/types';
import type {PlainDate} from './dateTypes';
import {
+ dateTimeFormatAtCall,
dateTimeFormatFor,
plainDateAddDays,
plainDateAddMonths,
- plainDateFormat,
plainDateFormatDayNumber,
plainDateFormatStandaloneMonthYear,
plainDateFormatToParts,
+ plainDateFromDate,
+ plainDateFromInstant,
plainDateIsInRange,
getDaysInMonth,
} from './plainDate';
@@ -380,7 +382,7 @@ 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, its day from Temporal, and its weekday from the date.
+ * the Temporal month, and its day from Temporal.
*/
export function formatCalendarDate(
calendar: CalendarSystem,
@@ -388,15 +390,32 @@ export function formatCalendarDate(
options: Intl.DateTimeFormatOptions,
locale: Locale,
): string {
- if (isGregorianAligned(calendar)) {
- return plainDateFormat(
- pd,
- {...options, calendar: labelCalendar(calendar)},
- locale,
- );
+ return joinParts(formatCalendarDateToParts(calendar, pd, options, locale));
+}
+
+/** The parts of `formatCalendarDate`'s label. */
+export function formatCalendarDateToParts(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+): Intl.DateTimeFormatPart[] {
+ const parts = formatToParts(labelCalendar(calendar), pd, options, locale);
+ return withTemporalDay(calendar, pd, parts, options, locale);
+}
+
+// Returns `parts` itself where Intl already names Temporal's month and day.
+function withTemporalDay(
+ calendar: CalendarSystem,
+ pd: PlainDate,
+ parts: Intl.DateTimeFormatPart[],
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+): Intl.DateTimeFormatPart[] {
+ if (isGregorianAligned(calendar) || !isCalendarSystemAvailable(calendar)) {
+ return parts;
}
const date = inCalendar(calendar, pd);
- const parts = formatToParts(calendar, pd, options, locale);
const middle = plainDateAddDays(
pd,
Math.floor(date.daysInMonth / 2) - (date.day - 1),
@@ -412,23 +431,71 @@ export function formatCalendarDate(
Number(intlDay) === date.day &&
monthPartsKey(parts) === monthPartsKey(middleParts)
) {
- return parts.map(part => part.value).join('');
+ return parts;
}
const {numberingSystem} = dateTimeFormatFor(locale, {
...options,
calendar,
timeZone: 'UTC',
}).resolvedOptions();
- const weekday = parts.find(part => part.type === 'weekday')?.value;
- return middleParts
- .map(part =>
- part.type === 'day'
- ? plainDateFormatDayNumber(date.day, locale, numberingSystem)
- : part.type === 'weekday' && weekday != null
- ? weekday
- : part.value,
- )
- .join('');
+ const middleValues = new Map(
+ middleParts.map(part => [part.type, part.value]),
+ );
+ return parts.map(part =>
+ part.type === 'day'
+ ? {
+ ...part,
+ value: plainDateFormatDayNumber(date.day, locale, numberingSystem),
+ }
+ : MONTH_PART_TYPES.has(part.type)
+ ? {...part, value: middleValues.get(part.type) ?? part.value}
+ : part,
+ );
+}
+
+/**
+ * Formats an instant as `formatCalendarDate` formats the day it falls on in
+ * `timeZone`, the host's zone when omitted. Intl writes any time of day that
+ * `options` asks for.
+ */
+export function formatCalendarInstant(
+ calendar: CalendarSystem,
+ instant: Date,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+ timeZone?: string,
+): string {
+ return instantLabel(calendar, instant, options, locale, timeZone).text;
+}
+
+function instantLabel(
+ calendar: CalendarSystem,
+ instant: Date,
+ options: Intl.DateTimeFormatOptions,
+ locale: Locale,
+ timeZone: string | undefined,
+) {
+ const format = dateTimeFormatAtCall(locale, {
+ ...options,
+ ...(timeZone === undefined ? {} : {timeZone}),
+ calendar: labelCalendar(calendar),
+ });
+ const parts = format.formatToParts(instant);
+ const day =
+ timeZone === undefined
+ ? plainDateFromDate(instant)
+ : plainDateFromInstant(instant.getTime(), timeZone);
+ const fixed = withTemporalDay(calendar, day, parts, options, locale);
+ const isIntl = fixed === parts;
+ return {
+ format,
+ isIntl,
+ text: isIntl ? format.format(instant) : joinParts(fixed),
+ };
+}
+
+function joinParts(parts: Intl.DateTimeFormatPart[]): string {
+ return parts.map(part => part.value).join('');
}
/**
diff --git a/packages/core/src/utils/plainDate.test.ts b/packages/core/src/utils/plainDate.test.ts
index a4481989b2..af6f5ca942 100644
--- a/packages/core/src/utils/plainDate.test.ts
+++ b/packages/core/src/utils/plainDate.test.ts
@@ -32,6 +32,7 @@ import {
plainDateWeekdayNames,
plainDateFormatDayNumber,
formatSharedDate,
+ SHARED_DATE_FORMAT_OPTIONS,
DATE_FORMAT_LONG,
DATE_FORMAT_WITH_WEEKDAY,
DATE_FORMAT_MONTH_YEAR,
@@ -962,6 +963,47 @@ describe('formatSharedDate', () => {
expect(formatSharedDate(pd, 'system_date')).toBe('2026-01-25');
});
+ describe.each([
+ {calendar: 'persian', locale: 'en', year: '1405'},
+ {calendar: 'persian', locale: 'fa', year: '۱۴۰۵'},
+ {calendar: 'hebrew', locale: 'en', year: '5787'},
+ {calendar: 'hebrew', locale: 'he', year: '5787'},
+ {calendar: 'buddhist', locale: 'en', year: '2569'},
+ {calendar: 'buddhist', locale: 'th', year: '2569'},
+ ] as const)('in $calendar under $locale', ({calendar, locale, year}) => {
+ const day: PlainDate = {year: 2026, month: 10, day: 30};
+
+ it.each(['date', 'date_long', 'date_weekday'] as const)(
+ 'writes %s in the calendar',
+ format => {
+ const value = formatSharedDate(day, format, locale, calendar);
+ expect(value).toBe(
+ plainDateFormat(
+ day,
+ {...SHARED_DATE_FORMAT_OPTIONS[format], calendar},
+ locale,
+ ),
+ );
+ expect(value).toContain(year);
+ expect(value).not.toContain('2026');
+ },
+ );
+
+ it('keeps system_date Gregorian ISO', () => {
+ expect(formatSharedDate(day, 'system_date', locale, calendar)).toBe(
+ '2026-10-30',
+ );
+ });
+ });
+
+ it('defaults to the Gregorian calendar', () => {
+ const day: PlainDate = {year: 2026, month: 10, day: 30};
+ expect(formatSharedDate(day, 'date_long', 'fa')).toBe(
+ formatSharedDate(day, 'date_long', 'fa', 'gregory'),
+ );
+ expect(formatSharedDate(day, 'date_long', 'en')).toBe('October 30, 2026');
+ });
+
it('follows the passed locale rather than the host locale (#5074)', () => {
expect(formatSharedDate(pd, 'date_long', 'es-ES')).toBe(
'25 de enero de 2026',
diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.ts
index 11a2552097..5af6ee6e08 100644
--- a/packages/core/src/utils/plainDate.ts
+++ b/packages/core/src/utils/plainDate.ts
@@ -9,6 +9,11 @@
import type {ISODateString, PlainDate} from './dateTypes';
import type {Locale} from '../i18n/types';
+import {
+ formatCalendarDate,
+ isCalendarSystem,
+ type CalendarSystem,
+} from './calendarSystem';
import {firstCharacter} from './characters';
import {standaloneMonthCapitalLanguages} from './standaloneMonthCapitals.generated';
@@ -455,13 +460,18 @@ export const DATE_FORMAT_SHORT_WITH_YEAR: Intl.DateTimeFormatOptions = {
* when `options.calendar` is omitted. The explicit option remains supported for
* compatibility with the public `Intl.DateTimeFormatOptions` signature; it is a
* display-only escape hatch and does not change PlainDate arithmetic, parsing,
- * serialization, or any Astryx component's calendar semantics.
+ * serialization, or any Astryx component's calendar semantics. Another
+ * calendar names the month and day that Calendar shows in it.
*/
export function plainDateFormat(
pd: PlainDate,
options: Intl.DateTimeFormatOptions,
locale: Locale = 'en',
): string {
+ const calendar = options.calendar ?? 'gregory';
+ if (calendar !== 'gregory' && isCalendarSystem(calendar)) {
+ return formatCalendarDate(calendar, pd, options, locale);
+ }
const [format, date] = plainDateFormatInput(pd, options, locale);
return format.format(date);
}
@@ -546,6 +556,20 @@ export function dateTimeFormatFor(
return format;
}
+/**
+ * @internal `dateTimeFormatFor`, except that without `options.timeZone` it
+ * builds a formatter for the call. A cached formatter keeps the host zone it
+ * was built in.
+ */
+export function dateTimeFormatAtCall(
+ locale: Locale,
+ options: Intl.DateTimeFormatOptions,
+): Intl.DateTimeFormat {
+ return options.timeZone === undefined
+ ? new Intl.DateTimeFormat(locale, options)
+ : dateTimeFormatFor(locale, options);
+}
+
/**
* The locale's name for the "week of year" date field ("week", "Woche", "週"),
* from CLDR through `Intl.DisplayNames`. Calendar names its week-number
@@ -639,14 +663,21 @@ export const SHARED_DATE_FORMAT_OPTIONS: Record<
* members. The shared entry point DateInput uses for the named-format path;
* Timestamp maps the same members onto {@link SHARED_DATE_FORMAT_OPTIONS} in
* its own `formatTimestamp` switch (its input is a `Date`, not a `PlainDate`).
+ * The locale-aware members write the date in `calendar`, which defaults to
+ * Gregorian. `system_date` stays the Gregorian ISO date in every calendar.
*/
export function formatSharedDate(
pd: PlainDate,
format: SharedDateFormat,
locale: Locale = 'en',
+ calendar: CalendarSystem = 'gregory',
): string {
if (format === 'system_date') {
return plainDateToISO(pd);
}
- return plainDateFormat(pd, SHARED_DATE_FORMAT_OPTIONS[format], locale);
+ return plainDateFormat(
+ pd,
+ {...SHARED_DATE_FORMAT_OPTIONS[format], calendar},
+ locale,
+ );
}
diff --git a/packages/lab/src/Chart/formatters.test.ts b/packages/lab/src/Chart/formatters.test.ts
index eb91a5b31e..973361bf54 100644
--- a/packages/lab/src/Chart/formatters.test.ts
+++ b/packages/lab/src/Chart/formatters.test.ts
@@ -23,6 +23,42 @@ describe('Chart date formatters', () => {
);
});
+ it.each([
+ {calendar: 'persian', locale: 'en', year: '1405'},
+ {calendar: 'persian', locale: 'fa', year: '۱۴۰۵'},
+ {calendar: 'hebrew', locale: 'en', year: '5787'},
+ {calendar: 'hebrew', locale: 'he', year: '5787'},
+ {calendar: 'buddhist', locale: 'en', year: '2569'},
+ {calendar: 'buddhist', locale: 'th', year: '2569'},
+ ] as const)(
+ 'formats dates in an explicit $calendar calendar under $locale',
+ ({calendar, locale, year}) => {
+ const day = new Date(2026, 9, 30, 12);
+ expect(shortDate(day, locale, calendar)).toBe(
+ new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ day: 'numeric',
+ calendar,
+ }).format(day),
+ );
+ const label = monthYear(day, locale, calendar);
+ expect(label).toBe(
+ new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ year: 'numeric',
+ calendar,
+ }).format(day),
+ );
+ expect(label).toContain(year);
+ },
+ );
+
+ it('writes `iso8601` dates as Gregorian ones', () => {
+ const day = new Date(2026, 9, 30, 12);
+ expect(shortDate(day, 'en', 'iso8601')).toBe(shortDate(day, 'en'));
+ expect(monthYear(day, 'en', 'iso8601')).toBe('Oct 2026');
+ });
+
it('uses an explicit locale for unabridged currency values', () => {
expect(currency('€', 'de-DE')(12.5)).toBe(
`€${(12.5).toLocaleString('de-DE')}`,
diff --git a/packages/lab/src/Chart/formatters.ts b/packages/lab/src/Chart/formatters.ts
index 826d182efd..3220195409 100644
--- a/packages/lab/src/Chart/formatters.ts
+++ b/packages/lab/src/Chart/formatters.ts
@@ -2,12 +2,14 @@
/**
* @file formatters.ts
- * @input Tick values and optional BCP 47 locale tags
+ * @input Tick values, optional BCP 47 locale tags, and for dates an optional
+ * calendar
* @output Built-in tick format utilities for common data types
* @position Utility; consumed by ChartAxis via tickFormat prop
*/
-import type {Locale} from '@astryxdesign/core/i18n';
+import type {CalendarSystem, Locale} from '@astryxdesign/core/i18n';
+import {plainDateFormat, plainDateFromDate} from '@astryxdesign/core/utils';
/**
* Compact number formatter (e.g. 1200 → "1.2K", 1500000 → "1.5M")
@@ -79,31 +81,41 @@ export function percent(value: unknown): string {
}
/**
- * Date formatter — short date (e.g. "Jan 5", "Mar 12")
+ * Date formatter — short date (e.g. "Jan 5", "Mar 12"), in `calendar`
+ * (Gregorian by default)
*/
-export function shortDate(value: unknown, locale: Locale = 'en'): string {
+export function shortDate(
+ value: unknown,
+ locale: Locale = 'en',
+ calendar: CalendarSystem = 'gregory',
+): string {
const d = value instanceof Date ? value : new Date(Number(value));
if (isNaN(d.getTime())) {
return String(value);
}
- return new Intl.DateTimeFormat(locale, {
- month: 'short',
- day: 'numeric',
- calendar: 'gregory',
- }).format(d);
+ return plainDateFormat(
+ plainDateFromDate(d),
+ {month: 'short', day: 'numeric', calendar},
+ locale,
+ );
}
/**
- * Date formatter — month/year (e.g. "Jan 2024", "Mar 2025")
+ * Date formatter — month/year (e.g. "Jan 2024", "Mar 2025"), in `calendar`
+ * (Gregorian by default)
*/
-export function monthYear(value: unknown, locale: Locale = 'en'): string {
+export function monthYear(
+ value: unknown,
+ locale: Locale = 'en',
+ calendar: CalendarSystem = 'gregory',
+): string {
const d = value instanceof Date ? value : new Date(Number(value));
if (isNaN(d.getTime())) {
return String(value);
}
- return new Intl.DateTimeFormat(locale, {
- month: 'short',
- year: 'numeric',
- calendar: 'gregory',
- }).format(d);
+ return plainDateFormat(
+ plainDateFromDate(d),
+ {month: 'short', year: 'numeric', calendar},
+ locale,
+ );
}