Skip to content

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

TypeScript

fix(i18n): harden date locale handling (#5303)

nynexman44642458b03b35a4
diff --git a/.changeset/fix-plaindateformat-runtime-locale.md b/.changeset/fix-plaindateformat-runtime-locale.md
new file mode 100644
index 0000000000..cc4dc4d8ca
--- /dev/null
+++ b/.changeset/fix-plaindateformat-runtime-locale.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Date formatting now defaults to Gregorian calendar semantics across core, charts, and Schedule while still following the selected locale for language, numbering, and field order.
+
+The low-level public `plainDateFormat` helper continues to honor an explicitly supplied `calendar` option for compatibility; Astryx components do not expose that display-only exception and remain Gregorian. The deterministic English fallback also prevents server and browser locale differences from producing hydration mismatches when no provider locale is available. Locale-aware parsing only selects day-first or month-first order for ambiguous ASCII numeric dates; it does not parse localized month names, non-ASCII digits, or arbitrary locale-specific strings.
+
+Fixes #5074.
+
+@josephfarina
diff --git a/apps/storybook/stories/DateLocaleConsistency.stories.tsx b/apps/storybook/stories/DateLocaleConsistency.stories.tsx
new file mode 100644
index 0000000000..79a982b175
--- /dev/null
+++ b/apps/storybook/stories/DateLocaleConsistency.stories.tsx
@@ -0,0 +1,95 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file DateLocaleConsistency.stories.tsx
+ * @input InternationalizationProvider locale plus a fixed Gregorian date
+ * @output Side-by-side French and Thai date-formatting evidence
+ * @position Storybook verification story for shared date semantics
+ */
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import * as stylex from '@stylexjs/stylex';
+import {Calendar, type ISODateString} from '@astryxdesign/core/Calendar';
+import {DateInput} from '@astryxdesign/core/DateInput';
+import {
+ InternationalizationProvider,
+ type Locale,
+} from '@astryxdesign/core/i18n';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {Timestamp} from '@astryxdesign/core/Timestamp';
+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+
+const meta = {
+ title: 'Foundations/Internationalization/Date consistency',
+ parameters: {
+ layout: 'padded',
+ },
+} satisfies Meta;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+const DATE = '2026-08-22' as ISODateString;
+
+function LocaleDateExamples({locale}: {locale: Locale}) {
+ const [value, setValue] = useState<ISODateString | undefined>(DATE);
+
+ return (
+ <InternationalizationProvider locale={locale}>
+ <section
+ aria-label={`${locale} date examples`}
+ {...stylex.props(styles.panel)}>
+ <Heading level={2}>{locale}</Heading>
+ <DateInput
+ label="Selected date"
+ value={value}
+ onChange={setValue}
+ format="date_long"
+ nativePicker="never"
+ />
+ <Text>
+ Timestamp:{' '}
+ <Timestamp value="2026-08-22T12:00:00Z" format="date_long" />
+ </Text>
+ <Calendar
+ mode="single"
+ value={value}
+ onChange={setValue}
+ focusDate="2026-08-01"
+ />
+ </section>
+ </InternationalizationProvider>
+ );
+}
+
+export const FrenchAndThaiGregorian: Story = {
+ render: () => (
+ <div {...stylex.props(styles.comparison)}>
+ <LocaleDateExamples locale="fr-FR" />
+ <LocaleDateExamples locale="th-TH" />
+ </div>
+ ),
+ parameters: {
+ docs: {
+ description: {
+ story:
+ 'Calendar, DateInput, and Timestamp all follow the provider locale while preserving Gregorian year 2026. Thai must not render Buddhist year 2569.',
+ },
+ },
+ },
+};
+
+const styles = stylex.create({
+ comparison: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(2, minmax(0, 1fr))',
+ gap: spacingVars['--spacing-8'],
+ },
+ panel: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-4'],
+ minWidth: 0,
+ },
+});
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 4ef19fc3e1..398bac97fc 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -21,7 +21,7 @@ This plugin implements a two-tier linting strategy:
### `@astryx/no-raw-intl-locale`
`InternationalizationProvider` is the sole user-facing locale source. This
-rule forbids two independent things, anywhere in the lint scope:
+rule forbids three independent things, anywhere in the lint scope:
1. **Raw `Intl` access** — constructing a locale-sensitive `Intl` formatter,
calling `toLocaleString`/`toLocaleDateString`/`toLocaleTimeString`/
@@ -40,12 +40,17 @@ Intl.DateTimeFormat`), destructuring (`const {DateTimeFormat} = Intl`),
_any_ position, not only as an argument to an `Intl`/locale-method call.
`recognition.lang = lang ?? navigator.language` is flagged even though no
`Intl` API is involved.
+3. **Date-helper calls without a locale** — calls to `plainDateFormat`,
+ `formatSharedDate`, `parseDateInput`, and `isLocaleDayFirst` imported from
+ the Astryx helper modules must pass their locale argument. The rule follows
+ named imports, aliases, and namespace imports without matching unrelated
+ local functions that happen to use the same name.
Shipped component code should read the locale through the public
provider-aware utilities instead — `useLocale()`/`useCollator()` (exported
-from `@astryxdesign/core/i18n`) — or an existing formatting helper such as
-`plainDateFormat`/`formatInstant`/`formatFilterValue`, so the value always
-traces back to the provider.
+from `@astryxdesign/core/i18n`) — or use an existing formatting helper such as
+`plainDateFormat`/`formatInstant`/`formatFilterValue`. Date-helper callers pass
+`useLocale()` explicitly so the value always traces back to the provider.
**Raw `Intl` is controlled by two closed file lists in the rule source:**
@@ -53,11 +58,12 @@ traces back to the provider.
implementations. Direct Intl calls there still require a syntactically
explicit locale; `Intl.NumberFormat(undefined)`, an omitted locale, and
locale methods without their locale argument are errors. Aliasing or
- destructuring Intl is also rejected. The only temporary ambient exceptions
- are the existing calls inside the named `plainDateFormat` and
- `isLocaleDayFirst` functions, pending #5120.
+ destructuring Intl is also rejected.
- `APPROVED_TEST_ORACLE_FILES` contains named tests that deliberately construct
independent Intl expectations so assertions are not circular.
+- `DATE_HELPER_DEFAULT_TEST_FILES` contains only the two helper suites that
+ verify the backward-compatible default locale. This exemption applies only
+ to the helper-call locale requirement, not to raw Intl or navigator access.
Approved implementations:
@@ -84,6 +90,11 @@ Named test oracles:
- `packages/core/src/PowerSearch/formatFilterValue.test.ts`
- `packages/core/src/Timestamp/Timestamp.test.tsx`
+Named helper-default test files:
+
+- `packages/core/src/utils/plainDate.test.ts`
+- `packages/core/src/utils/dateParser.test.ts`
+
These lists are the **only** exception mechanism. There is no rule option or
`eslint.config.js` override that widens them. A new entry requires a rule-source
change and a focused rule test. `navigator.language`/`navigator.languages`
diff --git a/internal/eslint-plugin-astryx/index.js b/internal/eslint-plugin-astryx/index.js
index 9721b4e441..da46230d49 100644
--- a/internal/eslint-plugin-astryx/index.js
+++ b/internal/eslint-plugin-astryx/index.js
@@ -11,7 +11,7 @@
* - no-raw-paragraph: Disallows components from rendering a <p> by default (render <div> so any content composes)
* - no-style-only-wrapper: Disallows div/span wrappers that only style a single Astryx component (use xstyle)
* - no-nullish-jsx-guard: Flags `!= null` JSX render guards for rendered values (use isRenderable so false/''/true slots don't leak an empty element)
- * - no-raw-intl-locale: Forbids raw Intl formatting/comparison outside the approved i18n infrastructure boundary, and navigator.language(s) as a locale source
+ * - no-raw-intl-locale: Forbids raw Intl formatting/comparison outside the approved i18n infrastructure boundary, navigator.language(s) as a locale source, and date-helper calls without provider locale
* - no-unguarded-ime-keydown: Flags an onKeyDown on an editable surface that branches on command keys without an IME composition guard (isImeKeyEvent/isComposing)
* - no-classname-clobber: Flags two className sources on one JSX element — a literal className/style beside {...stylex.props()}, or two spreads that each carry a className (the later one silently wins)
* - no-hover-on-disabled: Flags a :hover condition that can still match a disabled element (browsers suppress a disabled control's events, not its hover styling)
diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.js b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
index aec523a874..611cd7d09a 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.js
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
@@ -15,15 +15,16 @@
* `@astryxdesign/core/i18n`, or an existing formatting helper such as
* `plainDateFormat`/`formatInstant`/`formatFilterValue`) — never construct an
* `Intl` formatter or call a locale-sensitive prototype method directly.
+ * Calls to the public date helpers are tracked through named imports, aliases,
+ * and namespace imports and must pass their locale argument explicitly.
* Passing an explicit locale expression does not satisfy this rule: a
* hardcoded literal, `navigator.language`, or an arbitrary variable are all
* still raw Intl access from the policy's point of view.
*
* Raw `Intl` is confined to two short, explicit lists below. Approved
* implementations may call Intl directly but still require an explicit locale;
- * named test-oracle files may construct independent expected values. The only
- * ambient implementation exceptions are the two named legacy helper bodies
- * pending #5120. No ESLint option can widen these boundaries.
+ * named test-oracle files may construct independent expected values. No ESLint
+ * option can widen these boundaries.
*
* `navigator.language`/`navigator.languages` are rejected everywhere,
* including inside an approved infrastructure file — the provider is the
@@ -102,8 +103,7 @@ const LOCALE_FIRST_METHODS = new Set([
* every added file requires a rule-source change and focused rule test.
*/
const APPROVED_IMPLEMENTATION_FILES = [
- // Date formatting/parsing core. The two pre-existing ambient call sites are
- // separately constrained by LEGACY_AMBIENT_CALLS below until #5120 lands.
+ // Date formatting/parsing core.
'packages/core/src/utils/plainDate.ts',
'packages/core/src/utils/dateParser.ts',
// Timestamp's shared instant formatter and its tooltip zone resolution
@@ -133,12 +133,30 @@ const APPROVED_TEST_ORACLE_FILES = [
'packages/core/src/Timestamp/Timestamp.test.tsx',
];
-// Temporary compatibility exceptions for the two public helpers whose locale
-// parameters are still pending in #5120. Scope by file + enclosing function,
-// not by file, so a second ambient formatter in either module is rejected.
-const LEGACY_AMBIENT_CALLS = new Map([
- ['packages/core/src/utils/plainDate.ts', new Set(['plainDateFormat'])],
- ['packages/core/src/utils/dateParser.ts', new Set(['isLocaleDayFirst'])],
+// These exact helper suites are the public default-behavior oracles. Production
+// callers must pass locale explicitly even though the public APIs retain their
+// deterministic defaults for backward compatibility.
+const DATE_HELPER_DEFAULT_TEST_FILES = [
+ 'packages/core/src/utils/plainDate.test.ts',
+ 'packages/core/src/utils/dateParser.test.ts',
+];
+
+const DATE_HELPER_LOCALE_ARGUMENTS = new Map([
+ ['plainDateFormat', 2],
+ ['formatSharedDate', 2],
+ ['parseDateInput', 1],
+ ['isLocaleDayFirst', 0],
+]);
+
+const DATE_HELPER_IMPLEMENTATION_FILES = new Map([
+ [
+ 'packages/core/src/utils/plainDate.ts',
+ new Set(['plainDateFormat', 'formatSharedDate']),
+ ],
+ [
+ 'packages/core/src/utils/dateParser.ts',
+ new Set(['parseDateInput', 'isLocaleDayFirst']),
+ ],
]);
function unwrap(node) {
@@ -278,25 +296,115 @@ function isListedFile(filename, approvedFiles) {
return approvedFiles.some(approved => normalized.endsWith(approved));
}
-function enclosingFunctionName(node) {
- let current = node.parent;
- while (current != null) {
- if (current.type === 'FunctionDeclaration') {
- return current.id?.name ?? null;
+function findVariable(sourceCode, identifier) {
+ let scope = sourceCode.getScope(identifier);
+ while (scope) {
+ const variable = scope.set?.get(identifier.name);
+ if (variable) {
+ return variable;
}
- current = current.parent;
+ scope = scope.upper;
}
return null;
}
-function isLegacyAmbientCall(filename, node) {
+function importSourceForSpecifier(specifier) {
+ const declaration = specifier?.parent;
+ return declaration?.type === 'ImportDeclaration' ? declaration.source : null;
+}
+
+function isDateHelperModule(source) {
+ if (typeof source?.value !== 'string') {
+ return false;
+ }
+ const value = source.value.replace(/\\/g, '/');
+ if (
+ value === '@astryxdesign/core' ||
+ value === '@astryxdesign/core/utils' ||
+ value.startsWith('@astryxdesign/core/utils/')
+ ) {
+ return true;
+ }
+ if (!value.startsWith('.')) {
+ return false;
+ }
+ return (
+ /(?:^|\/)(?:utils\/)?(?:plainDate|dateParser)$/.test(value) ||
+ /(?:^|\/)utils$/.test(value)
+ );
+}
+
+function importedName(specifier) {
+ const imported = specifier?.imported;
+ if (imported?.type === 'Identifier') {
+ return imported.name;
+ }
+ return typeof imported?.value === 'string' ? imported.value : null;
+}
+
+function importedDateHelperName(sourceCode, callee) {
+ if (callee?.type === 'Identifier') {
+ const variable = findVariable(sourceCode, callee);
+ const definition = variable?.defs.find(
+ def =>
+ def.type === 'ImportBinding' && def.node?.type === 'ImportSpecifier',
+ );
+ if (
+ definition &&
+ isDateHelperModule(importSourceForSpecifier(definition.node))
+ ) {
+ const name = importedName(definition.node);
+ return DATE_HELPER_LOCALE_ARGUMENTS.has(name) ? name : null;
+ }
+ return null;
+ }
+
+ if (callee?.type !== 'MemberExpression') {
+ return null;
+ }
+ const object = unwrap(callee.object);
+ if (object?.type !== 'Identifier') {
+ return null;
+ }
+ const variable = findVariable(sourceCode, object);
+ const definition = variable?.defs.find(
+ def =>
+ def.type === 'ImportBinding' &&
+ def.node?.type === 'ImportNamespaceSpecifier',
+ );
+ if (
+ !definition ||
+ !isDateHelperModule(importSourceForSpecifier(definition.node))
+ ) {
+ return null;
+ }
+ const name = staticPropertyName(callee);
+ return DATE_HELPER_LOCALE_ARGUMENTS.has(name) ? name : null;
+}
+
+function localDateHelperName(sourceCode, filename, callee) {
+ if (callee?.type !== 'Identifier') {
+ return null;
+ }
const normalized = normalizeFilename(filename);
- for (const [approved, functionNames] of LEGACY_AMBIENT_CALLS) {
- if (normalized.endsWith(approved)) {
- return functionNames.has(enclosingFunctionName(node));
+ let allowedNames = null;
+ for (const [implementationFile, names] of DATE_HELPER_IMPLEMENTATION_FILES) {
+ if (normalized.endsWith(implementationFile)) {
+ allowedNames = names;
+ break;
}
}
- return false;
+ if (!allowedNames?.has(callee.name)) {
+ return null;
+ }
+ const variable = findVariable(sourceCode, callee);
+ const isFunctionDeclaration = variable?.defs.some(
+ def =>
+ def.type === 'FunctionName' &&
+ def.node?.type === 'FunctionDeclaration' &&
+ def.node.id?.name === callee.name,
+ );
+ return isFunctionDeclaration ? callee.name : null;
}
/**
@@ -313,10 +421,7 @@ function isNonReferencePosition(identifier) {
if (!parent) {
return false;
}
- if (
- parent.type === 'TSQualifiedName' &&
- parent.left === identifier
- ) {
+ if (parent.type === 'TSQualifiedName' && parent.left === identifier) {
// Type-only reference such as `collator: Intl.Collator`; it emits no
// runtime Intl access and is part of the public TypeScript contract.
return true;
@@ -359,7 +464,7 @@ const rule = {
type: 'problem',
docs: {
description:
- 'Forbid raw Intl access (calls, aliasing, destructuring, computed indexing) outside the approved i18n infrastructure boundary; forbid navigator.language(s) as a locale source anywhere',
+ 'Forbid raw Intl access outside approved infrastructure, navigator.language(s) as a locale source, and date-helper calls that omit provider locale',
category: 'Best Practices',
recommended: true,
},
@@ -385,9 +490,12 @@ const rule = {
'(useLocale()/useCollator() from @astryxdesign/core/i18n) instead.',
ambientIntlInImplementation:
'Approved Intl implementation files must still pass an explicit locale. ' +
- 'A missing, undefined, or void locale would reintroduce host-dependent ' +
- 'behavior; only the two named legacy helper call sites are temporarily ' +
- 'exempt until #5120 lands.',
+ 'A missing, undefined, or void locale would reintroduce host-dependent behavior.',
+ dateHelperLocale:
+ 'Pass the provider locale explicitly to {{helper}}. Read it with ' +
+ 'useLocale() in React code and thread it into pure helpers; omitted or ' +
+ 'undefined locale arguments fall back deterministically but do not ' +
+ 'follow InternationalizationProvider.',
navigatorLocale:
'Do not source a locale from navigator.language/navigator.languages, ' +
'in any position — not only as an argument to Intl or a locale ' +
@@ -451,10 +559,7 @@ const rule = {
// Named tests may build independent Intl oracles, including the host
// default where that is the behavior under test.
} else if (implementationFile) {
- if (
- isUndefinedExpression(localeArg) &&
- !isLegacyAmbientCall(filename, node)
- ) {
+ if (isUndefinedExpression(localeArg)) {
report(node, 'ambientIntlInImplementation');
}
} else {
@@ -492,6 +597,31 @@ const rule = {
}
}
+ function checkDateHelperCall(node) {
+ if (isListedFile(filename, DATE_HELPER_DEFAULT_TEST_FILES)) {
+ return;
+ }
+ const callee = unwrap(node.callee);
+ const helper =
+ importedDateHelperName(sourceCode, callee) ??
+ localDateHelperName(sourceCode, filename, callee);
+ if (!helper) {
+ return;
+ }
+ const localeArgumentIndex = DATE_HELPER_LOCALE_ARGUMENTS.get(helper);
+ const localeArgument = node.arguments[localeArgumentIndex];
+ if (
+ isUndefinedExpression(localeArgument) ||
+ localeArgument?.type === 'SpreadElement'
+ ) {
+ context.report({
+ node,
+ messageId: 'dateHelperLocale',
+ data: {helper},
+ });
+ }
+ }
+
return {
NewExpression(node) {
checkIntlFormatter(node);
@@ -500,6 +630,7 @@ const rule = {
if (!checkIntlFormatter(node)) {
checkLocaleMethod(node);
}
+ checkDateHelperCall(node);
},
// Unconditional: navigator.language/languages is never an acceptable
diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
index fd7a21aced..efcacffb4a 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
@@ -25,6 +25,7 @@ const ambientIntlInImplementation = {
messageId: 'ambientIntlInImplementation',
};
const navigatorLocale = {messageId: 'navigatorLocale'};
+const dateHelperLocale = {messageId: 'dateHelperLocale'};
// A file outside the approved infrastructure allowlist — the common case for
// shipped component code. Used as the default `filename` for every case that
@@ -40,8 +41,10 @@ const NUMBER_PARSER_TEST_ORACLE_FILE =
const NUMBER_PARSER_DOCBLOCK_ORACLE_FILE =
'packages/core/src/NumberInput/numberParser.docblock.test.ts';
const CHARTS_INFRA_FILE = 'packages/charts/src/formatters.ts';
-const TIMESTAMP_TEST_ORACLE_FILE = 'packages/core/src/Timestamp/Timestamp.test.tsx';
-const CALENDAR_TEST_ORACLE_FILE = 'packages/core/src/Calendar/Calendar.test.tsx';
+const TIMESTAMP_TEST_ORACLE_FILE =
+ 'packages/core/src/Timestamp/Timestamp.test.tsx';
+const CALENDAR_TEST_ORACLE_FILE =
+ 'packages/core/src/Calendar/Calendar.test.tsx';
// A test file that is NOT one of the named oracle exceptions — proves the
// allowlist is exact-file, not "any *.test.tsx".
const OTHER_TEST_FILE = 'packages/core/src/DateInput/DateInput.test.tsx';
@@ -111,17 +114,10 @@ tester.run('no-raw-intl-locale', rule, {
filename: INFRA_FILE,
},
{code: `new Intl.NumberFormat(locale).format(123);`, filename: INFRA_FILE},
- {code: `new Intl.DateTimeFormat('en-US', {timeZone});`, filename: INFRA_FILE},
- // -- The only ambient implementation calls are the two named legacy
- // helpers pending #5120. A second call in either file is invalid. --
{
- code: `function plainDateFormat() { return new Intl.DateTimeFormat(undefined, options); }`,
+ code: `new Intl.DateTimeFormat('en-US', {timeZone});`,
filename: INFRA_FILE,
},
- {
- code: `function isLocaleDayFirst() { return new Intl.DateTimeFormat(); }`,
- filename: DATE_PARSER_INFRA_FILE,
- },
{code: `value.toLocaleString(locale);`, filename: INFRA_FILE},
{code: `left.localeCompare(right, locale);`, filename: INFRA_FILE},
{
@@ -143,7 +139,8 @@ tester.run('no-raw-intl-locale', rule, {
},
{
code: `left.localeCompare(right, 'en-US');`,
- filename: 'packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx',
+ filename:
+ 'packages/core/src/Table/plugins/tree/useTableTreeState.test.tsx',
},
{
code: `new Intl.NumberFormat('de-DE').format(1234234234);`,
@@ -166,6 +163,44 @@ tester.run('no-raw-intl-locale', rule, {
filename: CALENDAR_TEST_ORACLE_FILE,
},
+ // -- Date helper calls resolve through real imports and pass locale. --
+ {
+ code: `import {plainDateFormat, formatSharedDate} from '../utils/plainDate'; plainDateFormat(date, options, locale); formatSharedDate(date, format, locale);`,
+ filename: COMPONENT_FILE,
+ },
+ {
+ code: `import {parseDateInput as parse, isLocaleDayFirst as dayFirst} from '../utils'; parse(value, locale); dayFirst(locale);`,
+ filename: COMPONENT_FILE,
+ },
+ {
+ code: `import * as dateHelpers from '../utils/plainDate'; dateHelpers.plainDateFormat(date, options, locale); dateHelpers['formatSharedDate'](date, format, locale);`,
+ filename: COMPONENT_FILE,
+ },
+ {
+ code: `function plainDateFormat(date, options) { return value; } plainDateFormat(date, options);`,
+ filename: COMPONENT_FILE,
+ },
+ {
+ code: `import {plainDateFormat} from 'another-library'; plainDateFormat(date, options);`,
+ filename: COMPONENT_FILE,
+ },
+ {
+ code: `import {plainDateFormat} from '../utils/plainDate'; function render(plainDateFormat) { return plainDateFormat(date, options); }`,
+ filename: COMPONENT_FILE,
+ },
+ {
+ code: `function plainDateFormat(date, options, locale) { return value; } plainDateFormat(date, options, locale);`,
+ filename: INFRA_FILE,
+ },
+ {
+ code: `import {plainDateFormat} from './plainDate'; plainDateFormat(date, options);`,
+ filename: 'packages/core/src/utils/plainDate.test.ts',
+ },
+ {
+ code: `import {parseDateInput} from './dateParser'; parseDateInput(value);`,
+ filename: 'packages/core/src/utils/dateParser.test.ts',
+ },
+
// -- KNOWN GAP (syntax-only limitation, documented in the rule's file
// doc and README): a computed method name held in a variable cannot
// be resolved to 'toLocaleString' (or any other name) without
@@ -180,6 +215,43 @@ tester.run('no-raw-intl-locale', rule, {
],
invalid: [
+ // -- Production date-helper calls must pass the provider locale. --
+ {
+ code: `import {plainDateFormat} from '../utils/plainDate'; plainDateFormat(date, options);`,
+ filename: COMPONENT_FILE,
+ errors: [dateHelperLocale],
+ },
+ {
+ code: `import {formatSharedDate} from '../utils/plainDate'; formatSharedDate(date, format, undefined);`,
+ filename: COMPONENT_FILE,
+ errors: [dateHelperLocale],
+ },
+ {
+ code: `import {parseDateInput as parse} from '../utils'; parse(value);`,
+ filename: COMPONENT_FILE,
+ errors: [dateHelperLocale],
+ },
+ {
+ code: `import * as dateHelpers from '../utils/dateParser'; dateHelpers.isLocaleDayFirst();`,
+ filename: COMPONENT_FILE,
+ errors: [dateHelperLocale],
+ },
+ {
+ code: `import * as dateHelpers from '../utils/plainDate'; dateHelpers['plainDateFormat'](date, options);`,
+ filename: COMPONENT_FILE,
+ errors: [dateHelperLocale],
+ },
+ {
+ code: `function plainDateFormat(date, options, locale) { return value; } plainDateFormat(date, options);`,
+ filename: INFRA_FILE,
+ errors: [dateHelperLocale],
+ },
+ {
+ code: `function isLocaleDayFirst(locale) { return false; } isLocaleDayFirst();`,
+ filename: DATE_PARSER_INFRA_FILE,
+ errors: [dateHelperLocale],
+ },
+
// -- Approved implementation files still reject ambient locale calls and
// indirect Intl references. --
{
@@ -197,6 +269,16 @@ tester.run('no-raw-intl-locale', rule, {
filename: CHARTS_INFRA_FILE,
errors: [ambientIntlInImplementation],
},
+ {
+ code: `function plainDateFormat() { return new Intl.DateTimeFormat(undefined, options); }`,
+ filename: INFRA_FILE,
+ errors: [ambientIntlInImplementation],
+ },
+ {
+ code: `function isLocaleDayFirst() { return new Intl.DateTimeFormat(); }`,
+ filename: DATE_PARSER_INFRA_FILE,
+ errors: [ambientIntlInImplementation],
+ },
{
code: `function anotherFormatter() { return new Intl.DateTimeFormat(undefined, options); }`,
filename: INFRA_FILE,
@@ -232,7 +314,11 @@ tester.run('no-raw-intl-locale', rule, {
errors: [rawIntlLocale],
},
// -- Nor does a missing/ambient locale, as before --
- {code: `new Intl.DateTimeFormat();`, filename: COMPONENT_FILE, errors: [rawIntlLocale]},
+ {
+ code: `new Intl.DateTimeFormat();`,
+ filename: COMPONENT_FILE,
+ errors: [rawIntlLocale],
+ },
{
code: `Intl.NumberFormat(undefined);`,
filename: COMPONENT_FILE,
@@ -285,7 +371,11 @@ tester.run('no-raw-intl-locale', rule, {
errors: [rawIntlLocale],
},
// -- Locale-sensitive prototype methods, with or without a locale arg --
- {code: `value.toLocaleString();`, filename: COMPONENT_FILE, errors: [rawIntlLocale]},
+ {
+ code: `value.toLocaleString();`,
+ filename: COMPONENT_FILE,
+ errors: [rawIntlLocale],
+ },
{
code: `value.toLocaleString(locale);`,
filename: COMPONENT_FILE,
diff --git a/packages/charts/src/formatters.test.ts b/packages/charts/src/formatters.test.ts
index bfc794bf55..a42f8c8ac3 100644
--- a/packages/charts/src/formatters.test.ts
+++ b/packages/charts/src/formatters.test.ts
@@ -67,6 +67,25 @@ describe('chart formatters', () => {
expect(shortDate(value, 'de-DE')).not.toBe(shortDate(value, 'en-US'));
});
+ it('keeps Gregorian dates for locales that default to another calendar', () => {
+ const value = '2026-08-22';
+ const date = new Date(2026, 7, 22);
+ expect(shortDate(value, 'fa-IR')).toBe(
+ new Intl.DateTimeFormat('fa-IR', {
+ month: 'short',
+ day: 'numeric',
+ calendar: 'gregory',
+ }).format(date),
+ );
+ expect(monthYear(value, 'th-TH')).toBe(
+ new Intl.DateTimeFormat('th-TH', {
+ month: 'short',
+ year: 'numeric',
+ calendar: 'gregory',
+ }).format(date),
+ );
+ });
+
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 63d51806b9..780bc69b05 100644
--- a/packages/charts/src/formatters.ts
+++ b/packages/charts/src/formatters.ts
@@ -46,11 +46,21 @@ const getPercentFormat = byLocale(
);
const getShortDateFormat = byLocale(
- locale => new Intl.DateTimeFormat(locale, {month: 'short', day: 'numeric'}),
+ locale =>
+ new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ day: 'numeric',
+ calendar: 'gregory',
+ }),
);
const getMonthYearFormat = byLocale(
- locale => new Intl.DateTimeFormat(locale, {month: 'short', year: 'numeric'}),
+ locale =>
+ new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ year: 'numeric',
+ calendar: 'gregory',
+ }),
);
/**
diff --git a/packages/core/src/Calendar/Calendar.test.tsx b/packages/core/src/Calendar/Calendar.test.tsx
index 5363775cd7..ce2965270d 100644
--- a/packages/core/src/Calendar/Calendar.test.tsx
+++ b/packages/core/src/Calendar/Calendar.test.tsx
@@ -165,6 +165,27 @@ describe('Calendar', () => {
).toEqual([...localizedNames.slice(1), localizedNames[0]]);
});
+ it('updates the month header and subsequent navigation with provider locale', async () => {
+ const user = userEvent.setup();
+ const renderCalendar = (locale: 'en-US' | 'es-ES') => (
+ <InternationalizationProvider locale={locale}>
+ <Calendar focusDate="2026-01-01" />
+ </InternationalizationProvider>
+ );
+ const {rerender} = render(renderCalendar('en-US'));
+
+ expect(screen.getByText('January 2026')).toBeInTheDocument();
+
+ rerender(renderCalendar('es-ES'));
+ expect(screen.getByText('enero de 2026')).toBeInTheDocument();
+
+ const nextButton =
+ document.querySelector<HTMLButtonElement>('[data-nav="next"]');
+ expect(nextButton).not.toBeNull();
+ await user.click(nextButton!);
+ expect(screen.getByText('febrero de 2026')).toBeInTheDocument();
+ });
+
it('displays correct number of day cells', () => {
render(<Calendar />);
diff --git a/packages/core/src/Calendar/Calendar.tsx b/packages/core/src/Calendar/Calendar.tsx
index 13d62b98c8..71795ea008 100644
--- a/packages/core/src/Calendar/Calendar.tsx
+++ b/packages/core/src/Calendar/Calendar.tsx
@@ -19,7 +19,6 @@
*/
import {
- use,
useState,
useMemo,
useCallback,
@@ -90,7 +89,7 @@ import type {
} from '../utils/dateTypes';
import {normalizeDayOfWeek} from '../utils/dateTypes';
import {themeProps} from '../utils/themeProps';
-import {useTranslator, InternationalizationContext} from '../i18n';
+import {useLocale, useTranslator} from '../i18n';
/** Imperative handle for Calendar handleRef */
@@ -228,7 +227,7 @@ export type CalendarProps = CalendarSingleProps | CalendarRangeProps;
*/
export function Calendar({ref, ...props}: CalendarProps) {
const t = useTranslator();
- const {locale} = use(InternationalizationContext);
+ const locale = useLocale();
const {
handleRef,
mode = 'single',
@@ -654,7 +653,7 @@ function MonthGrid({
pendingFocus,
onPendingFocusHandled,
}: MonthGridProps) {
- const {locale} = use(InternationalizationContext);
+ const locale = useLocale();
const year = month.year;
// Use hooks for days generation and constraints
@@ -1035,7 +1034,7 @@ function DayCell({
onDayHover,
}: DayCellProps) {
const t = useTranslator();
- const {locale} = use(InternationalizationContext);
+ const locale = useLocale();
const {date, isOutside, dayNumber} = day;
if (isOutside && !hasOutsideDays) {
diff --git a/packages/core/src/Calendar/hooks/useCalendarDays.ts b/packages/core/src/Calendar/hooks/useCalendarDays.ts
index 2295f795fd..10aac9ef09 100644
--- a/packages/core/src/Calendar/hooks/useCalendarDays.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarDays.ts
@@ -4,7 +4,7 @@
/**
* @file useCalendarDays.ts
- * @input Uses React context via use(), useMemo, PlainDate utilities, generated CLDR weekday data
+ * @input Uses React useMemo, useLocale, PlainDate utilities, generated CLDR weekday data
* @output Exports useCalendarDays hook for generating calendar day grids
* @position Calendar-specific hook; used by Calendar
*
@@ -12,7 +12,7 @@
* - /packages/core/src/Calendar/hooks/index.ts
*/
-import {use, useMemo} from 'react';
+import {useMemo} from 'react';
import type {DayOfWeek, ISODateString} from '../../utils/dateTypes';
import {
type PlainDate,
@@ -21,7 +21,7 @@ import {
plainDateDayOfWeek,
plainDateAddDays,
} from '../../utils/plainDate';
-import {InternationalizationContext} from '../../i18n/InternationalizationContext';
+import {useLocale} from '../../i18n';
import {getStandaloneShortWeekdayNames} from '../getStandaloneShortWeekdayNames';
/**
@@ -86,7 +86,7 @@ export function useCalendarDays(
options: UseCalendarDaysOptions,
): UseCalendarDaysReturn {
const {year, month, weekStartsOn = 0, hasVariableRowCount = false} = options;
- const {locale} = use(InternationalizationContext);
+ const locale = useLocale();
// Calculate grid structure
const gridInfo = useMemo(() => {
diff --git a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
index 306e98a0d0..04f7311de7 100644
--- a/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
+++ b/packages/core/src/Calendar/hooks/useCalendarNavigation.ts
@@ -4,7 +4,7 @@
/**
* @file useCalendarNavigation.ts
- * @input Uses React useState, useMemo, useCallback, PlainDate utilities
+ * @input Uses React useState, useMemo, useCallback, useLocale, PlainDate utilities
* @output Exports useCalendarNavigation hook for month navigation
* @position Calendar-specific hook; used by Calendar
*
@@ -12,7 +12,7 @@
* - /packages/core/src/Calendar/hooks/index.ts
*/
-import {use, useState, useMemo, useCallback} from 'react';
+import {useState, useMemo, useCallback} from 'react';
import type {ISODateString} from '../../utils/dateTypes';
import {
type PlainDate,
@@ -25,7 +25,7 @@ import {
plainDateFormat,
DATE_FORMAT_MONTH_YEAR,
} from '../../utils/plainDate';
-import {InternationalizationContext} from '../../i18n';
+import {useLocale} from '../../i18n';
/**
* Configuration for calendar navigation
@@ -99,7 +99,7 @@ export function useCalendarNavigation(
onFocusDateChange,
numberOfMonths = 1,
} = options;
- const {locale} = use(InternationalizationContext);
+ const locale = useLocale();
// Pending focus target after month navigation
const [pendingFocus, setPendingFocus] = useState<ISODateString | null>(null);
diff --git a/packages/core/src/DateInput/DateInput.test.tsx b/packages/core/src/DateInput/DateInput.test.tsx
index cd98872524..76b9508695 100644
--- a/packages/core/src/DateInput/DateInput.test.tsx
+++ b/packages/core/src/DateInput/DateInput.test.tsx
@@ -917,17 +917,22 @@ describe('DateInput', () => {
expect(screen.getByDisplayValue('Jan 25, 2026')).toBeInTheDocument();
});
- it('follows the InternationalizationProvider locale (#5074)', () => {
- render(
- <InternationalizationProvider locale="es-ES">
+ it('updates when the InternationalizationProvider locale changes (#5074)', () => {
+ const renderDateInput = (locale: 'en-US' | 'es-ES') => (
+ <InternationalizationProvider locale={locale}>
<DateInput
label="Date"
value="2026-01-25"
onChange={() => {}}
format="date_long"
/>
- </InternationalizationProvider>,
+ </InternationalizationProvider>
);
+ const {rerender} = render(renderDateInput('en-US'));
+
+ expect(screen.getByDisplayValue('January 25, 2026')).toBeInTheDocument();
+
+ rerender(renderDateInput('es-ES'));
expect(
screen.getByDisplayValue('25 de enero de 2026'),
).toBeInTheDocument();
diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsx
index 363654e6d1..2692ef2f99 100644
--- a/packages/core/src/DateInput/DateInput.tsx
+++ b/packages/core/src/DateInput/DateInput.tsx
@@ -17,7 +17,6 @@
*/
import {
- use,
useId,
useState,
useCallback,
@@ -179,7 +178,7 @@ import type {SizeValue} from '../utils/types';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {stableClassName} from '../naming';
-import {useTranslator, InternationalizationContext} from '../i18n';
+import {useLocale, useTranslator} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
export interface DateInputProps extends Omit<
@@ -465,8 +464,8 @@ function PointerDateField({
...rest
}: DateInputProps) {
const t = useTranslator();
+ const locale = useLocale();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
- const {locale} = use(InternationalizationContext);
const placeholder =
placeholderFromProps ?? t('@astryx.dateInput.placeholder');
const size = useSize(sizeProp, 'md');
diff --git a/packages/core/src/DateInput/DateInputTouch.test.tsx b/packages/core/src/DateInput/DateInputTouch.test.tsx
index 7147849c49..f07301fbe4 100644
--- a/packages/core/src/DateInput/DateInputTouch.test.tsx
+++ b/packages/core/src/DateInput/DateInputTouch.test.tsx
@@ -41,6 +41,7 @@ import {fileURLToPath} from 'node:url';
import {useState} from 'react';
import type {ISODateString} from '../utils';
import {InputGroup} from '../InputGroup';
+import {InternationalizationProvider} from '../i18n';
import {stableClassName} from '../naming';
import {DateInput} from './DateInput';
import {
@@ -357,6 +358,41 @@ describe('DateInput — surface selection', () => {
expect(input).toHaveAttribute('inputmode', 'none');
});
+ it('updates the field and open picker when the provider locale changes', () => {
+ const renderDateInput = (locale: 'en-US' | 'es-ES') => (
+ <InternationalizationProvider locale={locale}>
+ <Controlled initial="2026-03-21" />
+ </InternationalizationProvider>
+ );
+
+ withLayout(() => {
+ const {rerender} = render(renderDateInput('en-US'));
+ expect(field()).toHaveValue('March 21, 2026');
+
+ fireEvent.click(field());
+ expect(
+ document.querySelector('[data-title="month-year"]'),
+ ).toHaveTextContent('March 2026');
+ expect(pane('March 2026')).toBeInTheDocument();
+
+ rerender(renderDateInput('es-ES'));
+ expect(field()).toHaveValue('21 de marzo de 2026');
+ expect(
+ document.querySelector('[data-title="month-year"]'),
+ ).toHaveTextContent('marzo de 2026');
+ expect(pane('marzo de 2026')).toBeInTheDocument();
+
+ const nextButton = document.querySelector<HTMLButtonElement>(
+ '[data-arrows="months"] button:last-child',
+ );
+ expect(nextButton).not.toBeNull();
+ fireEvent.click(nextButton!);
+ expect(
+ document.querySelector('[data-title="month-year"]'),
+ ).toHaveTextContent('abril de 2026');
+ });
+ });
+
it('forwards ref to the input on both surfaces', () => {
const desktopRef = {current: null as HTMLInputElement | null};
setViewport('desktop');
diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsx
index 9bf58082b4..f6816fa7ae 100644
--- a/packages/core/src/DateInput/MonthScroller.tsx
+++ b/packages/core/src/DateInput/MonthScroller.tsx
@@ -39,7 +39,7 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import {useCalendarDays} from '../Calendar';
-import {useDirection} from '../i18n';
+import {useDirection, useLocale} from '../i18n';
import {
colorVars,
radiusVars,
@@ -763,6 +763,7 @@ function MonthPane({
onDayKeyDown,
onDayFocus,
}: MonthPaneProps) {
+ const locale = useLocale();
const {year, month} = fromMonthIndex(monthIndex);
const {weeks} = useCalendarDays({
year,
@@ -776,6 +777,7 @@ function MonthPane({
const monthLabel = plainDateFormat(
{year, month, day: 1},
DATE_FORMAT_MONTH_YEAR,
+ locale,
);
// Exactly one day per pane is tab-reachable, so Tab moves through the
@@ -836,6 +838,7 @@ function MonthPane({
aria-label={plainDateFormat(
day.date,
DATE_FORMAT_WITH_WEEKDAY,
+ locale,
)}
aria-disabled={isDisabled || undefined}
aria-current={isToday ? 'date' : undefined}
diff --git a/packages/core/src/DateInput/MonthYearWheels.tsx b/packages/core/src/DateInput/MonthYearWheels.tsx
index 6ff9e2532a..d59b252f95 100644
--- a/packages/core/src/DateInput/MonthYearWheels.tsx
+++ b/packages/core/src/DateInput/MonthYearWheels.tsx
@@ -23,6 +23,7 @@
import {useMemo} from 'react';
import * as stylex from '@stylexjs/stylex';
+import {useLocale} from '../i18n';
import {DATE_FORMAT_MONTH_ONLY, plainDateFormat} from '../utils';
import {spacingVars} from '../theme/tokens.stylex';
import {dateInputTouchGeometry} from './tokens.stylex';
@@ -66,6 +67,7 @@ export function MonthYearWheels({
yearLabel,
isActive = true,
}: MonthYearWheelsProps) {
+ const locale = useLocale();
const {year, month} = fromMonthIndex(monthIndex);
// Day 15 of a fixed year: no timezone can push it into an adjacent month
@@ -73,18 +75,18 @@ export function MonthYearWheels({
//
// `plainDateFormat` rather than a raw `Intl.DateTimeFormat`, which the
// shared lint rule forbids and which would duplicate the format vocabulary
- // besides. It resolves the locale itself, so there is nothing here for the
- // memo to depend on — the same is true of Calendar's own month labels, and
- // is why this list is constant for the life of the component.
+ // besides. Recompute when the provider locale changes so the wheel labels
+ // stay in sync with the field and calendar.
const monthNames = useMemo(
() =>
Array.from({length: 12}, (_, index) =>
plainDateFormat(
{year: 2021, month: index + 1, day: 15},
DATE_FORMAT_MONTH_ONLY,
+ locale,
),
),
- [],
+ [locale],
);
// Months outside the range stay on the wheel rather than vanishing: a list
diff --git a/packages/core/src/DateInput/TouchDateField.tsx b/packages/core/src/DateInput/TouchDateField.tsx
index 2827d452b7..da6b46119f 100644
--- a/packages/core/src/DateInput/TouchDateField.tsx
+++ b/packages/core/src/DateInput/TouchDateField.tsx
@@ -75,7 +75,7 @@ import {useInputStatusIcon, useMergedRefs} from '../hooks';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {Icon} from '../Icon';
import {IconButton} from '../IconButton';
-import {useTranslator} from '../i18n';
+import {useLocale, useTranslator} from '../i18n';
import {useInputGroup} from '../InputGroup';
import {groupStyles} from '../InputGroup/groupStyles';
import {stableClassName} from '../naming';
@@ -574,6 +574,7 @@ export function TouchDateField({
...rest
}: DateInputProps) {
const t = useTranslator();
+ const locale = useLocale();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
const placeholder =
placeholderFromProps ?? t('@astryx.dateInput.placeholder');
@@ -699,13 +700,15 @@ export function TouchDateField({
plainDateFormat(
{year: 1970, month: 1, day: 4 + ((weekStartsOn + offset) % 7)},
DATE_FORMAT_WEEKDAY_ONLY,
+ locale,
),
),
- [weekStartsOn],
+ [locale, weekStartsOn],
);
const monthYearLabel = plainDateFormat(
{year, month, day: 1},
DATE_FORMAT_MONTH_YEAR,
+ locale,
);
// Formats the committed value only. A function format is called with the ISO
@@ -715,7 +718,7 @@ export function TouchDateField({
optimisticValue != null && /^\d{4}-\d{2}-\d{2}$/.test(optimisticValue)
? typeof format === 'function'
? format(optimisticValue)
- : formatSharedDate(plainDateFromISO(optimisticValue), format)
+ : formatSharedDate(plainDateFromISO(optimisticValue), format, locale)
: '';
const fireChange = useCallback(
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
index 7c93e407c4..96407726f9 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.test.tsx
@@ -27,6 +27,7 @@ import type {DateRange} from './DateRangeInput';
import {Icon} from '../Icon';
import {defineTheme} from '../theme/defineTheme';
import {generateThemeCSS} from '../theme/generateThemeRules';
+import {InternationalizationProvider} from '../i18n';
describe('DateRangeInput', () => {
it('renders with label', () => {
@@ -72,6 +73,29 @@ describe('DateRangeInput', () => {
expect(trigger.textContent).toMatch(/22/);
});
+ it('updates the committed range display when provider locale changes', () => {
+ const range: DateRange = {
+ start: '2025-01-02',
+ end: '2025-01-05',
+ };
+ const renderDateRangeInput = (locale: 'en-US' | 'es-ES') => (
+ <InternationalizationProvider locale={locale}>
+ <DateRangeInput
+ label="Range"
+ value={range}
+ onChange={() => {}}
+ hasClear={false}
+ />
+ </InternationalizationProvider>
+ );
+ const {rerender} = render(renderDateRangeInput('en-US'));
+
+ expect(screen.getByText('Jan 2, 2025 – Jan 5, 2025')).toBeInTheDocument();
+
+ rerender(renderDateRangeInput('es-ES'));
+ expect(screen.getByText('2 ene 2025 – 5 ene 2025')).toBeInTheDocument();
+ });
+
it('forwards ref to trigger button', () => {
const ref = vi.fn();
render(
diff --git a/packages/core/src/DateRangeInput/DateRangeInput.tsx b/packages/core/src/DateRangeInput/DateRangeInput.tsx
index a228108416..13a9b34a7a 100644
--- a/packages/core/src/DateRangeInput/DateRangeInput.tsx
+++ b/packages/core/src/DateRangeInput/DateRangeInput.tsx
@@ -16,14 +16,7 @@
* - /packages/cli/assets/templates/blocks/components/DateRangeInput/ (showcase blocks)
*/
-import {
- use,
- useId,
- useCallback,
- useMemo,
- useOptimistic,
- useTransition,
-} from 'react';
+import {useId, useCallback, useMemo, useOptimistic, useTransition} from 'react';
import * as stylex from '@stylexjs/stylex';
import {
plainDateFromISO,
@@ -72,7 +65,7 @@ import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
import {stableClassName} from '../naming';
-import {useTranslator, InternationalizationContext} from '../i18n';
+import {useLocale, useTranslator} from '../i18n';
import type {Locale} from '../i18n/types';
export type {DateRange} from '../Calendar';
@@ -202,7 +195,7 @@ const sizeStyles = stylex.create({
},
});
-function formatRangeDisplay(range: DateRange | null, locale?: Locale): string {
+function formatRangeDisplay(range: DateRange | null, locale: Locale): string {
if (!range) {
return '';
}
@@ -493,8 +486,8 @@ export function DateRangeInput({
...rest
}: DateRangeInputProps) {
const t = useTranslator();
+ const locale = useLocale();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
- const {locale} = use(InternationalizationContext);
const placeholder =
placeholderFromProps ?? t('@astryx.dateRangeInput.placeholder');
const size = useSize(sizeProp, 'md');
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
index 3357d8bafd..6f81940096 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.test.tsx
@@ -39,6 +39,24 @@ describe('DateTimeInput', () => {
expect(screen.getByLabelText('Meeting time')).toBeInTheDocument();
});
+ it('updates the committed date display when provider locale changes', () => {
+ const renderDateTimeInput = (locale: 'en-US' | 'es-ES') => (
+ <InternationalizationProvider locale={locale}>
+ <DateTimeInput
+ label="Meeting"
+ value={'2026-01-25T14:30' as ISODateTimeString}
+ onChange={() => {}}
+ />
+ </InternationalizationProvider>
+ );
+ const {rerender} = render(renderDateTimeInput('en-US'));
+
+ expect(screen.getByRole('combobox')).toHaveValue('January 25, 2026');
+
+ rerender(renderDateTimeInput('es-ES'));
+ expect(screen.getByRole('combobox')).toHaveValue('25 de enero de 2026');
+ });
+
it('derives the time input label from the field label (forms-15)', () => {
render(<DateTimeInput label="Meeting time" onChange={() => {}} />);
// Not a hardcoded "Time" — tied to the field label so it is localizable
diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsx
index ed5aa0b0f8..32d9153485 100644
--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx
+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx
@@ -17,7 +17,6 @@
*/
import {
- use,
useId,
useState,
useCallback,
@@ -92,7 +91,7 @@ import {useResolvedRequired} from '../hooks/useResolvedRequired';
import {useSize} from '../SizeContext/SizeContext';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
-import {useTranslator, InternationalizationContext} from '../i18n';
+import {useLocale, useTranslator} from '../i18n';
import {useMergedRefs} from '../hooks/useMergedRefs';
export type ISODateTimeString = string & {
@@ -533,8 +532,8 @@ export function DateTimeInput({
...rest
}: DateTimeInputProps) {
const t = useTranslator();
+ const locale = useLocale();
const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});
- const {locale} = use(InternationalizationContext);
// Speaks arrow-key stepping results through the persistent live regions:
// stepping programmatically rewrites a plain textbox's value, which screen
// readers do not announce on their own (WCAG 4.1.2).
diff --git a/packages/core/src/PowerSearch/formatFilterValue.test.ts b/packages/core/src/PowerSearch/formatFilterValue.test.ts
index 147d178842..70330ba4f3 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.test.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.test.ts
@@ -1,7 +1,11 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, expect, it} from 'vitest';
-import {formatFilterValue} from './formatFilterValue';
+import {
+ formatDateAbsolute,
+ formatDateAbsoluteCompact,
+ formatFilterValue,
+} from './formatFilterValue';
import type {TranslatorFn} from '../i18n';
import type {OperatorValue, FilterValue} from './types';
@@ -270,6 +274,17 @@ describe('formatFilterValue', () => {
),
).toBe('date range');
});
+ it('keeps Gregorian years for locales that default to another calendar', () => {
+ const unixSeconds = Date.parse('2026-08-22T12:00:00Z') / 1000;
+ for (const value of [
+ formatDateAbsolute(unixSeconds, 'th-TH', 'UTC'),
+ formatDateAbsoluteCompact(unixSeconds, 'th-TH'),
+ ]) {
+ expect(value).toContain('2026');
+ expect(value).not.toContain('2569');
+ }
+ });
+
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 ff01cbed77..d5490ae670 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.ts
@@ -44,6 +44,7 @@ export function formatDateAbsolute(
hour: 'numeric',
minute: '2-digit',
...(timezoneID ? {timeZone: timezoneID} : {}),
+ calendar: 'gregory',
};
return new Intl.DateTimeFormat(locale, options).format(unixSeconds * 1000);
}
@@ -63,6 +64,7 @@ export function formatDateAbsoluteCompact(
year: 'numeric',
month: 'short',
day: 'numeric',
+ calendar: 'gregory',
}).format(unixSeconds * 1000);
}
diff --git a/packages/core/src/Timestamp/Timestamp.test.tsx b/packages/core/src/Timestamp/Timestamp.test.tsx
index 689945e85a..7f190a1ce7 100644
--- a/packages/core/src/Timestamp/Timestamp.test.tsx
+++ b/packages/core/src/Timestamp/Timestamp.test.tsx
@@ -12,6 +12,7 @@ import {
import {render, screen, act, waitFor, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {Timestamp} from './Timestamp';
+import {formatInstant} from './formatInstant';
import {formatTooltipLines} from './tooltipEntries';
import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
import {InternationalizationProvider} from '../i18n';
@@ -277,6 +278,36 @@ describe('Timestamp', () => {
expect(screen.getByTestId('ts')).toHaveTextContent('25. Januar 2026');
});
+ it.each(['full', 'date', 'date_long', 'date_weekday', 'date_time'] as const)(
+ 'keeps Gregorian years for the %s format under a non-Gregorian locale',
+ format => {
+ const value = formatInstant(
+ new Date('2026-08-22T12:00:00Z'),
+ format,
+ 'th-TH',
+ {timeZone: 'UTC'},
+ );
+ expect(value).toContain('2026');
+ expect(value).not.toContain('2569');
+ },
+ );
+
+ it('keeps Gregorian years in Timestamp output under a non-Gregorian locale', () => {
+ render(
+ <InternationalizationProvider locale="th-TH">
+ <Timestamp
+ value="2026-08-22T12:00:00Z"
+ format="date_long"
+ hasTooltip={false}
+ data-testid="ts"
+ />
+ </InternationalizationProvider>,
+ );
+
+ expect(screen.getByTestId('ts')).toHaveTextContent('2026');
+ expect(screen.getByTestId('ts')).not.toHaveTextContent('2569');
+ });
+
it('renders date format', () => {
render(
<Timestamp value="2026-02-19T17:00:00Z" format="date" data-testid="ts" />,
diff --git a/packages/core/src/Timestamp/formatInstant.ts b/packages/core/src/Timestamp/formatInstant.ts
index 1a40316e61..f0ba7df322 100644
--- a/packages/core/src/Timestamp/formatInstant.ts
+++ b/packages/core/src/Timestamp/formatInstant.ts
@@ -182,24 +182,28 @@ export function formatInstant(
...FULL_OPTIONS,
timeZoneName: timeZoneNameStyle,
...zone,
+ calendar: 'gregory',
}).format(date);
case 'date':
return new Intl.DateTimeFormat(locale, {
...SHARED_DATE_FORMAT_OPTIONS.date,
...zone,
+ calendar: 'gregory',
}).format(date);
case 'date_long':
return new Intl.DateTimeFormat(locale, {
...SHARED_DATE_FORMAT_OPTIONS.date_long,
...zone,
+ calendar: 'gregory',
}).format(date);
case 'date_weekday':
return new Intl.DateTimeFormat(locale, {
...SHARED_DATE_FORMAT_OPTIONS.date_weekday,
...zone,
+ calendar: 'gregory',
}).format(date);
case 'date_time':
@@ -207,6 +211,7 @@ export function formatInstant(
...DATE_TIME_OPTIONS,
...zoneName,
...zone,
+ calendar: 'gregory',
}).format(date);
case 'time':
diff --git a/packages/core/src/utils/dateParser.test.ts b/packages/core/src/utils/dateParser.test.ts
index 246931e258..22040462fa 100644
--- a/packages/core/src/utils/dateParser.test.ts
+++ b/packages/core/src/utils/dateParser.test.ts
@@ -9,8 +9,8 @@
* SYNC: When dateParser.ts changes, update tests to match new behavior
*/
-import {describe, it, expect} from 'vitest';
-import {parseDateInput} from './dateParser';
+import {describe, it, expect, vi} from 'vitest';
+import {isLocaleDayFirst, parseDateInput} from './dateParser';
describe('parseDateInput', () => {
describe('ISO format (YYYY-MM-DD)', () => {
@@ -280,6 +280,14 @@ describe('parseDateInput', () => {
describe('ambiguous numeric formats follow the passed locale (#5074)', () => {
// Both numbers are <= 12, so the day/month order is genuinely ambiguous
// and resolved by isLocaleDayFirst(locale) rather than the host locale.
+ it('defaults ambiguous input to English month-first order', () => {
+ expect(parseDateInput('3/4/2026')).toEqual({
+ year: 2026,
+ month: 3,
+ day: 4,
+ });
+ });
+
it('reads month-first for en-US', () => {
expect(parseDateInput('3/4/2026', 'en-US')).toEqual({
year: 2026,
@@ -297,6 +305,30 @@ describe('parseDateInput', () => {
});
});
+ describe('isLocaleDayFirst', () => {
+ it('defaults to English month-first order', () => {
+ expect(isLocaleDayFirst()).toBe(false);
+ });
+
+ it('requests Gregorian calendar data for locale ordering', () => {
+ const OriginalDateTimeFormat = globalThis.Intl.DateTimeFormat;
+ const dateTimeFormatSpy = vi
+ .spyOn(globalThis.Intl, 'DateTimeFormat')
+ .mockImplementation(function DateTimeFormat(locale, options) {
+ return new OriginalDateTimeFormat(locale, options);
+ });
+
+ try {
+ isLocaleDayFirst('en-US-u-ca-buddhist');
+ expect(dateTimeFormatSpy).toHaveBeenCalledWith('en-US-u-ca-buddhist', {
+ calendar: 'gregory',
+ });
+ } finally {
+ dateTimeFormatSpy.mockRestore();
+ }
+ });
+ });
+
describe('edge cases', () => {
it('returns null for empty string', () => {
expect(parseDateInput('')).toBeNull();
diff --git a/packages/core/src/utils/dateParser.ts b/packages/core/src/utils/dateParser.ts
index d43d296387..fd82ec67a9 100644
--- a/packages/core/src/utils/dateParser.ts
+++ b/packages/core/src/utils/dateParser.ts
@@ -23,10 +23,10 @@ export {
* Detects if the locale uses day-first date format (DD/MM/YYYY).
* US and a few others use month-first (MM/DD/YYYY).
*/
-export function isLocaleDayFirst(locale?: Locale): boolean {
- const parts = new Intl.DateTimeFormat(locale).formatToParts(
- new Date(2000, 0, 15),
- );
+export function isLocaleDayFirst(locale: Locale = 'en'): boolean {
+ const parts = new Intl.DateTimeFormat(locale, {
+ calendar: 'gregory',
+ }).formatToParts(new Date(2000, 0, 15));
const dayIndex = parts.findIndex(p => p.type === 'day');
const monthIndex = parts.findIndex(p => p.type === 'month');
return dayIndex < monthIndex;
@@ -35,20 +35,17 @@ export function isLocaleDayFirst(locale?: Locale): boolean {
/**
* Parses user input into a PlainDate.
*
- * Supports:
- * - ISO format: "2026-01-25"
- * - Full month names: "January 25, 2026", "25 January 2026"
- * - Full month names without year: "January 25", "25 January" (defaults to current year)
- * - Numeric formats: "1/25/2026", "25/1/2026" (locale-aware with heuristics)
- * - Numeric formats without year: "1/25", "25/1" (defaults to current year)
- *
- * For ambiguous numeric formats (both numbers ≤ 12), uses locale preference.
+ * Supports ISO dates, English month names, and ASCII numeric dates with or
+ * without a year. For ambiguous ASCII numeric input where both fields are at
+ * most 12, `locale` selects month-first versus day-first order. It does not
+ * localize month-name parsing, accept non-ASCII digits, or provide a general
+ * locale-aware parser.
*
* @returns PlainDate if valid, null if unparseable
*/
export function parseDateInput(
input: string,
- locale?: Locale,
+ locale: Locale = 'en',
): PlainDate | null {
const trimmed = input.trim();
if (!trimmed) {
@@ -157,7 +154,7 @@ function parseNumericDate(
first: number,
second: number,
year: number,
- locale?: Locale,
+ locale: Locale,
): PlainDate | null {
let day: number;
let month: number;
diff --git a/packages/core/src/utils/plainDate.test.ts b/packages/core/src/utils/plainDate.test.ts
index 5b4c2b6905..7677b475f4 100644
--- a/packages/core/src/utils/plainDate.test.ts
+++ b/packages/core/src/utils/plainDate.test.ts
@@ -29,6 +29,7 @@ import {
plainDateFormat,
formatSharedDate,
DATE_FORMAT_WITH_WEEKDAY,
+ DATE_FORMAT_MONTH_YEAR,
} from './plainDate';
import type {ISODateString} from './dateTypes';
@@ -589,6 +590,51 @@ describe('plainDateFormat', () => {
expect(result).toContain('2026');
expect(result).toContain('25');
});
+
+ it('defaults to en when the locale is omitted', () => {
+ expect(
+ plainDateFormat({year: 2026, month: 8, day: 22}, DATE_FORMAT_MONTH_YEAR),
+ ).toBe('August 2026');
+ });
+
+ it('honors an explicit locale', () => {
+ expect(
+ plainDateFormat(
+ {year: 2026, month: 8, day: 22},
+ DATE_FORMAT_MONTH_YEAR,
+ 'fr',
+ ),
+ ).toBe('août 2026');
+ });
+
+ it('matches an explicit en locale when the locale is omitted', () => {
+ const pd: PlainDate = {year: 2026, month: 8, day: 22};
+ for (const options of [DATE_FORMAT_MONTH_YEAR, DATE_FORMAT_WITH_WEEKDAY]) {
+ expect(plainDateFormat(pd, options)).toBe(
+ plainDateFormat(pd, options, 'en'),
+ );
+ }
+ });
+
+ it('uses Gregorian fields for a non-Gregorian locale extension', () => {
+ expect(
+ plainDateFormat(
+ {year: 2026, month: 8, day: 22},
+ {year: 'numeric'},
+ 'en-US-u-ca-buddhist',
+ ),
+ ).toBe('2026');
+ });
+
+ it('honors an explicitly requested calendar for compatibility', () => {
+ expect(
+ plainDateFormat(
+ {year: 2026, month: 8, day: 22},
+ {year: 'numeric', calendar: 'buddhist'},
+ 'en-US',
+ ),
+ ).toBe('2569 BE');
+ });
});
describe('formatSharedDate', () => {
diff --git a/packages/core/src/utils/plainDate.ts b/packages/core/src/utils/plainDate.ts
index 36ee5ea588..a4d34d6a4d 100644
--- a/packages/core/src/utils/plainDate.ts
+++ b/packages/core/src/utils/plainDate.ts
@@ -130,6 +130,7 @@ export function getTimeZoneParts(
minute: '2-digit',
second: '2-digit',
hourCycle: 'h23',
+ calendar: 'gregory',
}).formatToParts(new Date(instant));
const lookup = Object.fromEntries(
@@ -307,12 +308,26 @@ export const DATE_FORMAT_SHORT_WITH_YEAR: Intl.DateTimeFormatOptions = {
year: 'numeric',
};
+/**
+ * Format a `PlainDate` for display.
+ *
+ * The locale defaults to the same `'en'` fallback as `useLocale()`, avoiding
+ * runtime-dependent output when no provider locale is available. Astryx date
+ * APIs currently model Gregorian dates, so this helper defaults to Gregorian
+ * 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.
+ */
export function plainDateFormat(
pd: PlainDate,
options: Intl.DateTimeFormatOptions,
- locale?: Locale,
+ locale: Locale = 'en',
): string {
- return new Intl.DateTimeFormat(locale, options).format(plainDateToDate(pd));
+ return new Intl.DateTimeFormat(locale, {
+ ...options,
+ calendar: options.calendar ?? 'gregory',
+ }).format(plainDateToDate(pd));
}
// =============================================================================
@@ -360,7 +375,7 @@ export const SHARED_DATE_FORMAT_OPTIONS: Record<
export function formatSharedDate(
pd: PlainDate,
format: SharedDateFormat,
- locale?: Locale,
+ locale: Locale = 'en',
): string {
if (format === 'system_date') {
return plainDateToISO(pd);
diff --git a/packages/lab/src/Chart/formatters.test.ts b/packages/lab/src/Chart/formatters.test.ts
new file mode 100644
index 0000000000..eb91a5b31e
--- /dev/null
+++ b/packages/lab/src/Chart/formatters.test.ts
@@ -0,0 +1,49 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {currency, monthYear, shortDate} from './formatters';
+
+describe('Chart date formatters', () => {
+ const date = new Date(2026, 7, 22, 12);
+
+ it('formats dates with the requested locale and Gregorian calendar', () => {
+ expect(shortDate(date, 'fr-FR')).toBe(
+ new Intl.DateTimeFormat('fr-FR', {
+ month: 'short',
+ day: 'numeric',
+ calendar: 'gregory',
+ }).format(date),
+ );
+ expect(monthYear(date, 'th-TH')).toBe(
+ new Intl.DateTimeFormat('th-TH', {
+ month: 'short',
+ year: 'numeric',
+ calendar: 'gregory',
+ }).format(date),
+ );
+ });
+
+ it('uses an explicit locale for unabridged currency values', () => {
+ expect(currency('€', 'de-DE')(12.5)).toBe(
+ `€${(12.5).toLocaleString('de-DE')}`,
+ );
+ expect(currency('€')(12.5)).toBe(`€${(12.5).toLocaleString('en')}`);
+ });
+
+ it('defaults to deterministic English Gregorian output', () => {
+ expect(shortDate(date)).toBe(
+ new Intl.DateTimeFormat('en', {
+ month: 'short',
+ day: 'numeric',
+ calendar: 'gregory',
+ }).format(date),
+ );
+ expect(monthYear(date)).toBe(
+ new Intl.DateTimeFormat('en', {
+ month: 'short',
+ year: 'numeric',
+ calendar: 'gregory',
+ }).format(date),
+ );
+ });
+});
diff --git a/packages/lab/src/Chart/formatters.ts b/packages/lab/src/Chart/formatters.ts
index 561463c532..826d182efd 100644
--- a/packages/lab/src/Chart/formatters.ts
+++ b/packages/lab/src/Chart/formatters.ts
@@ -2,10 +2,13 @@
/**
* @file formatters.ts
+ * @input Tick values and optional BCP 47 locale tags
* @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';
+
/**
* Compact number formatter (e.g. 1200 → "1.2K", 1500000 → "1.5M")
*/
@@ -36,7 +39,10 @@ export function compactNumber(value: unknown): string {
* <ChartAxis tickFormat={currency('¥')} /> // ¥1.5K
* ```
*/
-export function currency(symbol = '$'): (value: unknown) => string {
+export function currency(
+ symbol = '$',
+ locale: Locale = 'en',
+): (value: unknown) => string {
return (value: unknown) => {
const n = Number(value);
if (isNaN(n)) {
@@ -51,7 +57,7 @@ export function currency(symbol = '$'): (value: unknown) => string {
if (Math.abs(n) >= 1_000) {
return `${symbol}${strip(n / 1_000)}K`;
}
- return `${symbol}${n.toLocaleString()}`;
+ return `${symbol}${n.toLocaleString(locale)}`;
};
}
@@ -75,21 +81,29 @@ export function percent(value: unknown): string {
/**
* Date formatter — short date (e.g. "Jan 5", "Mar 12")
*/
-export function shortDate(value: unknown): string {
+export function shortDate(value: unknown, locale: Locale = 'en'): string {
const d = value instanceof Date ? value : new Date(Number(value));
if (isNaN(d.getTime())) {
return String(value);
}
- return d.toLocaleDateString(undefined, {month: 'short', day: 'numeric'});
+ return new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ day: 'numeric',
+ calendar: 'gregory',
+ }).format(d);
}
/**
* Date formatter — month/year (e.g. "Jan 2024", "Mar 2025")
*/
-export function monthYear(value: unknown): string {
+export function monthYear(value: unknown, locale: Locale = 'en'): string {
const d = value instanceof Date ? value : new Date(Number(value));
if (isNaN(d.getTime())) {
return String(value);
}
- return d.toLocaleDateString(undefined, {month: 'short', year: 'numeric'});
+ return new Intl.DateTimeFormat(locale, {
+ month: 'short',
+ year: 'numeric',
+ calendar: 'gregory',
+ }).format(d);
}
diff --git a/packages/lab/src/Schedule/DayView.tsx b/packages/lab/src/Schedule/DayView.tsx
index 4f09e63aab..69ec5c9ef4 100644
--- a/packages/lab/src/Schedule/DayView.tsx
+++ b/packages/lab/src/Schedule/DayView.tsx
@@ -34,12 +34,16 @@ export interface ScheduleDayViewOptions {
function ScheduleDayView({
options,
}: ScheduleViewComponentProps<ScheduleDayViewOptions>) {
- const {events, date, focusDate, timezoneID, range, isLoading} =
+ const {events, date, focusDate, timezoneID, locale, range, isLoading} =
useScheduleContext();
const {minHour = 0, maxHour = 24, hourHeight = 100} = options;
const rangeDate = date.toPlainDate();
const days = enumerateDates(range.startDate, range.endDate);
- const titleLabel = plainDateFormat(rangeDate, DATE_FORMAT_WITH_WEEKDAY);
+ const titleLabel = plainDateFormat(
+ rangeDate,
+ DATE_FORMAT_WITH_WEEKDAY,
+ locale,
+ );
return (
<ScheduleFrame
diff --git a/packages/lab/src/Schedule/ListView.tsx b/packages/lab/src/Schedule/ListView.tsx
index 0cb6754323..1cce3a9ba0 100644
--- a/packages/lab/src/Schedule/ListView.tsx
+++ b/packages/lab/src/Schedule/ListView.tsx
@@ -52,12 +52,18 @@ export interface ScheduleListViewOptions {
function ScheduleListView(
_props: ScheduleViewComponentProps<ScheduleListViewOptions>,
) {
- const {events, timezoneID, range, isLoading, headingLevel} = useScheduleContext();
+ const {events, timezoneID, locale, range, isLoading, headingLevel} =
+ useScheduleContext();
const days = enumerateDates(range.startDate, range.endDate);
const currentTime = useCurrentTime();
const currentPlainDate = plainDateFromInstant(currentTime, timezoneID);
const endDate = plainDateAddDays(range.endDate, -1);
- const titleLabel = formatWeekTitle(range.startDate, endDate, timezoneID);
+ const titleLabel = formatWeekTitle(
+ range.startDate,
+ endDate,
+ timezoneID,
+ locale,
+ );
const visibleDays = days
.map(day => {
const isCurrentDay = plainDateIsEqual(day, currentPlainDate);
@@ -125,12 +131,13 @@ function ListDayHeading({
timezoneID: string;
headingLevel: 2 | 3 | 4 | 5 | 6;
}) {
+ const {locale} = useScheduleContext();
return (
<Heading
level={headingLevel}
color="secondary"
display="block"
- aria-label={formatFullDate(day, timezoneID)}
+ aria-label={formatFullDate(day, timezoneID, locale)}
aria-current={isCurrentDay ? 'date' : undefined}
xstyle={styles.listDayHeading}>
<span
@@ -139,10 +146,10 @@ function ListDayHeading({
isCurrentDay && styles.listDayNumberCurrent,
)}>
<span {...stylex.props(styles.listDayNumberText)}>
- {formatDayNumber(day, timezoneID)}
+ {formatDayNumber(day, timezoneID, locale)}
</span>
</span>
- {formatWeekday(day, timezoneID, 'short')}
+ {formatWeekday(day, timezoneID, 'short', locale)}
</Heading>
);
}
diff --git a/packages/lab/src/Schedule/MonthlyView.tsx b/packages/lab/src/Schedule/MonthlyView.tsx
index d702e898ac..b390d86317 100644
--- a/packages/lab/src/Schedule/MonthlyView.tsx
+++ b/packages/lab/src/Schedule/MonthlyView.tsx
@@ -63,6 +63,7 @@ function ScheduleMonthlyView(
date,
focusDate,
timezoneID,
+ locale,
range,
isLoading,
headingLevel,
@@ -78,11 +79,11 @@ function ScheduleMonthlyView(
return (
<ScheduleFrame
title={<ScheduleMonthTitle date={rangeDate} timezoneID={timezoneID} />}
- titleLabel={formatMonthTitle(rangeDate, timezoneID)}
+ titleLabel={formatMonthTitle(rangeDate, timezoneID, locale)}
isLoading={isLoading}>
<div
role="grid"
- aria-label={formatMonthTitle(rangeDate, timezoneID)}
+ aria-label={formatMonthTitle(rangeDate, timezoneID, locale)}
aria-readonly
// The grid scrolls horizontally at narrow viewports and contains no
// focusable descendants, so it must be focusable itself for keyboard
@@ -94,7 +95,7 @@ function ScheduleMonthlyView(
<div
key={plainDateToISO(day)}
role="columnheader"
- aria-label={formatWeekday(day, timezoneID, 'long')}
+ aria-label={formatWeekday(day, timezoneID, 'long', locale)}
aria-colindex={index + 1}
{...stylex.props(styles.weekdayLabel)}>
<Heading
@@ -102,7 +103,7 @@ function ScheduleMonthlyView(
color="secondary"
display="block"
xstyle={styles.weekdayHeading}>
- {formatWeekday(day, timezoneID, 'short')}
+ {formatWeekday(day, timezoneID, 'short', locale)}
</Heading>
</div>
))}
@@ -123,7 +124,7 @@ function ScheduleMonthlyView(
<div
key={plainDateToISO(day)}
role="gridcell"
- aria-label={formatFullDate(day, timezoneID)}
+ aria-label={formatFullDate(day, timezoneID, locale)}
aria-colindex={dayIndex + 1}
aria-current={
plainDateIsEqual(day, highlightedDate)
@@ -147,7 +148,7 @@ function ScheduleMonthlyView(
color="inherit"
weight="medium"
hasTabularNumbers>
- {formatDayNumber(day, timezoneID)}
+ {formatDayNumber(day, timezoneID, locale)}
</Text>
</div>
{dayEvents.length > 0 && (
@@ -159,6 +160,7 @@ function ScheduleMonthlyView(
day,
timezoneID,
categories,
+ locale,
)}
</li>
))}
diff --git a/packages/lab/src/Schedule/Schedule.doc.mjs b/packages/lab/src/Schedule/Schedule.doc.mjs
index 1d195667ac..b8f6b06302 100644
--- a/packages/lab/src/Schedule/Schedule.doc.mjs
+++ b/packages/lab/src/Schedule/Schedule.doc.mjs
@@ -22,6 +22,11 @@ export const docs = {
description:
'Match the view to the density of the data: a month grid for at-a-glance load, a day or week time grid when start and end times matter, a list when the schedule is sparse.',
},
+ {
+ guidance: true,
+ description:
+ 'Wrap Schedule in InternationalizationProvider to choose the language, numbering, and field order used by its date and time labels. Schedule date values and calendar arithmetic remain Gregorian for every locale.',
+ },
{
guidance: true,
description:
diff --git a/packages/lab/src/Schedule/Schedule.test.tsx b/packages/lab/src/Schedule/Schedule.test.tsx
index 39c1c39e1b..f556e73560 100644
--- a/packages/lab/src/Schedule/Schedule.test.tsx
+++ b/packages/lab/src/Schedule/Schedule.test.tsx
@@ -2,6 +2,7 @@
import {describe, it, expect, vi} from 'vitest';
import {fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {InternationalizationProvider} from '@astryxdesign/core/i18n';
import {createEventFromISO} from './CalendarEvent';
import {Schedule} from './Schedule';
import {createScheduleDayView} from './DayView';
@@ -9,6 +10,7 @@ import {createScheduleListView} from './ListView';
import {createScheduleMonthlyView} from './MonthlyView';
import {createScheduleWeeklyView} from './WeeklyView';
import {sortEvents} from './dateMath';
+import {formatWithPlainDate} from './shared';
import {useScheduleViewSelectorPlugin} from './plugins/ViewSelectorPlugin';
import type {
CalendarEvent,
@@ -49,6 +51,41 @@ describe('createEventFromISO', () => {
});
});
+describe('Schedule date formatting', () => {
+ it('keeps Gregorian fields when options request another calendar', () => {
+ expect(
+ formatWithPlainDate(
+ {year: 2026, month: 8, day: 22},
+ 'UTC',
+ {
+ year: 'numeric',
+ calendar: 'buddhist',
+ },
+ 'en',
+ ),
+ ).toBe('2026');
+ });
+
+ it('formats Gregorian dates with the requested locale', () => {
+ const date = {year: 2026, month: 8, day: 22};
+ expect(
+ formatWithPlainDate(
+ date,
+ 'UTC',
+ {month: 'long', year: 'numeric'},
+ 'th-TH',
+ ),
+ ).toBe(
+ new Intl.DateTimeFormat('th-TH', {
+ month: 'long',
+ year: 'numeric',
+ timeZone: 'UTC',
+ calendar: 'gregory',
+ }).format(new Date(Date.UTC(2026, 7, 22, 12))),
+ );
+ });
+});
+
describe('Schedule', () => {
const categories: ScheduleCategory[] = [
{label: 'Sync', color: 'blue'},
@@ -99,6 +136,30 @@ describe('Schedule', () => {
expect(screen.queryByText('Outside range')).not.toBeInTheDocument();
});
+ it('renders monthly dates and times with the provider locale', async () => {
+ render(
+ <InternationalizationProvider locale="fr-FR">
+ <Schedule
+ view={createScheduleMonthlyView()}
+ events={events}
+ categories={categories}
+ date={Date.UTC(2026, 4, 13)}
+ focusDate={Date.UTC(2026, 4, 13)}
+ timezoneID="UTC"
+ />
+ </InternationalizationProvider>,
+ );
+
+ expect(screen.getByRole('heading', {name: 'mai 2026'})).toBeInTheDocument();
+ expect(screen.getByRole('grid', {name: 'mai 2026'})).toBeInTheDocument();
+ expect(
+ screen.getByRole('columnheader', {name: 'mercredi'}),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText('Visible sync, Sync, 16:00 - 16:30'),
+ ).toBeInTheDocument();
+ });
+
it('renders monthly weekday headings at the configured headingLevel (default 3)', async () => {
render(
<Schedule
diff --git a/packages/lab/src/Schedule/Schedule.tsx b/packages/lab/src/Schedule/Schedule.tsx
index 18c538579f..b5486aae78 100644
--- a/packages/lab/src/Schedule/Schedule.tsx
+++ b/packages/lab/src/Schedule/Schedule.tsx
@@ -4,7 +4,7 @@
/**
* @file Schedule.tsx
- * @input Calendar events, event loader functions, view objects, date/focusDate/timezone props
+ * @input Calendar events, event loader functions, view objects, date/focusDate/timezone props, and provider locale
* @output Generic read-only schedule shell that renders arbitrary schedule views
* @position Lab component shell; concrete views live in separate view files
*
@@ -17,6 +17,7 @@
import {Suspense, useCallback, useMemo, useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
+import {useLocale, type Locale} from '@astryxdesign/core/i18n';
import {mergeProps, plainDateFromInstant} from '@astryxdesign/core/utils';
import {eventOverlapsRange, getBrowserTimezoneID, sortEvents} from './dateMath';
import {ScheduleContext} from './context';
@@ -153,6 +154,7 @@ function ScheduleViewContent<Options extends ScheduleViewOptions>({
categories,
date,
focusDate,
+ locale,
isLoading,
onPreviousDate,
previousDateLabel,
@@ -167,6 +169,7 @@ function ScheduleViewContent<Options extends ScheduleViewOptions>({
categories: ReadonlyArray<ScheduleCategory>;
date: ZonedDateTime;
focusDate: ZonedDateTime;
+ locale: Locale;
isLoading: boolean;
onPreviousDate: () => void;
previousDateLabel: string;
@@ -190,6 +193,7 @@ function ScheduleViewContent<Options extends ScheduleViewOptions>({
date,
focusDate,
timezoneID: date.timezoneID,
+ locale,
range,
isLoading,
onPreviousDate,
@@ -221,6 +225,7 @@ export function Schedule({
style,
...rest
}: ScheduleProps) {
+ const locale = useLocale();
const timezoneID = timezoneIDProp ?? getBrowserTimezoneID();
const [internalFocusDate] = useState<Instant>(() => Date.now() as Instant);
const focusDate = focusDateProp ?? internalFocusDate;
@@ -284,6 +289,7 @@ export function Schedule({
categories={categories}
date={zonedDateTime}
focusDate={focusZonedDateTime}
+ locale={locale}
isLoading
onPreviousDate={onPreviousDate}
previousDateLabel={previousDateRange.label}
@@ -300,6 +306,7 @@ export function Schedule({
categories={categories}
date={zonedDateTime}
focusDate={focusZonedDateTime}
+ locale={locale}
isLoading={false}
onPreviousDate={onPreviousDate}
previousDateLabel={previousDateRange.label}
diff --git a/packages/lab/src/Schedule/TimeGridView.tsx b/packages/lab/src/Schedule/TimeGridView.tsx
index a543b897a4..b46ce8988a 100644
--- a/packages/lab/src/Schedule/TimeGridView.tsx
+++ b/packages/lab/src/Schedule/TimeGridView.tsx
@@ -10,6 +10,7 @@
*/
import * as stylex from '@stylexjs/stylex';
+import type {Locale} from '@astryxdesign/core/i18n';
import {
plainDateAddDays,
plainDateFromInstant,
@@ -65,7 +66,7 @@ export function TimeGridView({
maxHour: number;
hourHeight: number;
}) {
- const {categories, headingLevel} = useScheduleContext();
+ const {categories, headingLevel, locale} = useScheduleContext();
const normalizedMinHour = Math.max(0, Math.min(23, Math.floor(minHour)));
const normalizedMaxHour = Math.max(
normalizedMinHour + 1,
@@ -89,6 +90,7 @@ export function TimeGridView({
const timezoneLabel = formatTimezoneAbbreviation(
days[0] ?? focusDate,
timezoneID,
+ locale,
);
return (
@@ -100,6 +102,7 @@ export function TimeGridView({
events={instantEvents}
focusDate={focusDate}
hours={hours}
+ locale={locale}
timezoneID={timezoneID}
timezoneLabel={timezoneLabel}
/>
@@ -119,14 +122,14 @@ export function TimeGridView({
display="block"
xstyle={styles.timeGridHeaderHeading}>
<span {...stylex.props(styles.timeGridHeaderHeadingContent)}>
- {formatWeekday(day, timezoneID, 'short')}
+ {formatWeekday(day, timezoneID, 'short', locale)}
<span
{...stylex.props(
styles.timeGridDayNumber,
plainDateIsEqual(day, focusDate) &&
styles.timeGridCurrentDayPill,
)}>
- {formatDayNumber(day, timezoneID)}
+ {formatDayNumber(day, timezoneID, locale)}
</span>
</span>
</Heading>
@@ -187,7 +190,7 @@ export function TimeGridView({
styles.timeLabel,
styles.timeLabelPosition(index + 1, hourHeight),
)}>
- {formatHour(hour)}
+ {formatHour(hour, locale)}
</div>
))}
</div>
@@ -226,7 +229,12 @@ export function TimeGridView({
minHour: normalizedMinHour,
maxHour: normalizedMaxHour,
}).map(({event, height, level, top}) => {
- const timeLabel = formatEventTime(event, day, timezoneID);
+ const timeLabel = formatEventTime(
+ event,
+ day,
+ timezoneID,
+ locale,
+ );
const category = getEventCategory(event, categories);
return (
<div
@@ -284,6 +292,7 @@ function TimeGridAccessibilityGrid({
events,
focusDate,
hours,
+ locale,
timezoneID,
timezoneLabel,
}: {
@@ -293,6 +302,7 @@ function TimeGridAccessibilityGrid({
events: ReadonlyArray<CalendarInstantEvent>;
focusDate: PlainDate;
hours: ReadonlyArray<number>;
+ locale: Locale;
timezoneID: string;
timezoneLabel: string;
}) {
@@ -314,7 +324,7 @@ function TimeGridAccessibilityGrid({
aria-current={
plainDateIsEqual(day, focusDate) ? 'date' : undefined
}>
- {formatFullDate(day, timezoneID)}
+ {formatFullDate(day, timezoneID, locale)}
</div>
))}
</div>
@@ -335,7 +345,8 @@ function TimeGridAccessibilityGrid({
categories,
day,
events: cellEvents,
- label: `${formatFullDate(day, timezoneID)} all day`,
+ label: `${formatFullDate(day, timezoneID, locale)} all day`,
+ locale,
timezoneID,
})}
/>
@@ -345,7 +356,7 @@ function TimeGridAccessibilityGrid({
{hours.map(hour => (
<div key={hour} role="row">
<div role="rowheader" aria-colindex={1}>
- {formatHour(hour)}
+ {formatHour(hour, locale)}
</div>
{days.map((day, index) => {
const cellEvents = events.filter(event =>
@@ -360,9 +371,11 @@ function TimeGridAccessibilityGrid({
categories,
day,
events: cellEvents,
- label: `${formatFullDate(day, timezoneID)} ${formatHour(
+ label: `${formatFullDate(day, timezoneID, locale)} ${formatHour(
hour,
+ locale,
)}`,
+ locale,
timezoneID,
})}
/>
@@ -379,19 +392,21 @@ function formatTimeGridAccessibilityCellLabel({
day,
events,
label,
+ locale,
timezoneID,
}: {
categories: ReadonlyArray<ScheduleCategory>;
day: PlainDate;
events: ReadonlyArray<CalendarEvent>;
label: string;
+ locale: Locale;
timezoneID: string;
}): string {
if (events.length === 0) {
return label;
}
const eventLabels = events.map(event =>
- formatEventAccessibilityLabel(event, day, timezoneID, categories),
+ formatEventAccessibilityLabel(event, day, timezoneID, categories, locale),
);
return `${label}. ${eventLabels.join('. ')}`;
}
diff --git a/packages/lab/src/Schedule/WeeklyView.tsx b/packages/lab/src/Schedule/WeeklyView.tsx
index 38b42123ae..54acf8de17 100644
--- a/packages/lab/src/Schedule/WeeklyView.tsx
+++ b/packages/lab/src/Schedule/WeeklyView.tsx
@@ -9,7 +9,10 @@
* @position Concrete schedule view; exported as createScheduleWeeklyView
*/
-import {plainDateAddDays, plainDateSetStartOfWeek} from '@astryxdesign/core/utils';
+import {
+ plainDateAddDays,
+ plainDateSetStartOfWeek,
+} from '@astryxdesign/core/utils';
import {enumerateDates, getScheduleRangeFromDates} from './dateMath';
import {useScheduleContext} from './context';
import {
@@ -35,7 +38,7 @@ export interface ScheduleWeeklyViewOptions {
function ScheduleWeeklyView({
options,
}: ScheduleViewComponentProps<ScheduleWeeklyViewOptions>) {
- const {events, focusDate, timezoneID, range, isLoading} =
+ const {events, focusDate, timezoneID, locale, range, isLoading} =
useScheduleContext();
const {minHour = 0, maxHour = 24, hourHeight = 100} = options;
const days = enumerateDates(range.startDate, range.endDate);
@@ -44,6 +47,7 @@ function ScheduleWeeklyView({
days[0],
days[days.length - 1],
timezoneID,
+ locale,
);
return (
diff --git a/packages/lab/src/Schedule/context.tsx b/packages/lab/src/Schedule/context.tsx
index d603906f38..cc6ce325f5 100644
--- a/packages/lab/src/Schedule/context.tsx
+++ b/packages/lab/src/Schedule/context.tsx
@@ -4,12 +4,13 @@
/**
* @file context.tsx
- * @input Resolved Schedule events, range, timezone, and active date
+ * @input Resolved Schedule events, range, timezone, locale, and active date
* @output Schedule context object and hook used by view components
* @position Internal context bridge between generic Schedule and concrete views
*/
import {createContext, useContext} from 'react';
+import type {Locale} from '@astryxdesign/core/i18n';
import type {
CalendarEvent,
ScheduleRange,
@@ -25,6 +26,7 @@ export interface ScheduleContextValue {
date: ZonedDateTime;
focusDate: ZonedDateTime;
timezoneID: string;
+ locale: Locale;
range: ScheduleRange;
isLoading: boolean;
onPreviousDate: () => void;
@@ -38,9 +40,7 @@ export interface ScheduleContextValue {
headingLevel: 2 | 3 | 4 | 5 | 6;
}
-export const ScheduleContext = createContext<ScheduleContextValue | null>(
- null,
-);
+export const ScheduleContext = createContext<ScheduleContextValue | null>(null);
export function useScheduleContext(): ScheduleContextValue {
const context = useContext(ScheduleContext);
diff --git a/packages/lab/src/Schedule/shared.tsx b/packages/lab/src/Schedule/shared.tsx
index be3fac11b1..6f3459d6a2 100644
--- a/packages/lab/src/Schedule/shared.tsx
+++ b/packages/lab/src/Schedule/shared.tsx
@@ -4,13 +4,14 @@
/**
* @file shared.tsx
- * @input Schedule events, dates, timezone IDs, and display metadata
+ * @input Schedule events, dates, timezone IDs, provider locale, and display metadata
* @output Shared rendering primitives, formatters, and styles for schedule views
* @position Internal view utility module; consumed by Monthly, Weekly, Day, and List views
*/
import {type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
+import type {Locale} from '@astryxdesign/core/i18n';
import {
borderVars,
colorVars,
@@ -113,14 +114,36 @@ export function ScheduleMonthTitle({
date: PlainDate;
timezoneID: string;
}) {
- const month = new Intl.DateTimeFormat(undefined, {
+ const {locale} = useScheduleContext();
+ return (
+ <LocalizedMonthTitle date={date} timezoneID={timezoneID} locale={locale} />
+ );
+}
+
+function LocalizedMonthTitle({
+ date,
+ timezoneID,
+ locale,
+}: {
+ date: PlainDate;
+ timezoneID: string;
+ locale: Locale;
+}) {
+ const parts = new Intl.DateTimeFormat(locale, {
month: 'long',
+ year: 'numeric',
timeZone: timezoneID,
- }).format(new Date(Date.UTC(date.year, date.month - 1, date.day, 12)));
- return (
- <>
- <span {...stylex.props(styles.titleEmphasis)}>{month}</span> {date.year}
- </>
+ calendar: 'gregory',
+ }).formatToParts(new Date(plainDateToInstant(date, timezoneID, 12)));
+
+ return parts.map((part, index) =>
+ part.type === 'month' ? (
+ <span key={index} {...stylex.props(styles.titleEmphasis)}>
+ {part.value}
+ </span>
+ ) : (
+ part.value
+ ),
);
}
@@ -133,22 +156,33 @@ export function ScheduleRangeMonthTitle({
end: PlainDate;
timezoneID: string;
}) {
+ const {locale} = useScheduleContext();
if (start.year === end.year && start.month === end.month) {
return <ScheduleMonthTitle date={start} timezoneID={timezoneID} />;
}
- const startMonth = formatWithPlainDate(start, timezoneID, {month: 'long'});
- const endMonth = formatWithPlainDate(end, timezoneID, {month: 'long'});
+ const startMonth = formatWithPlainDate(
+ start,
+ timezoneID,
+ {month: 'long'},
+ locale,
+ );
+ const endMonthTitle = (
+ <LocalizedMonthTitle date={end} timezoneID={timezoneID} locale={locale} />
+ );
return start.year === end.year ? (
<>
<span {...stylex.props(styles.titleEmphasis)}>{startMonth}</span> -{' '}
- <span {...stylex.props(styles.titleEmphasis)}>{endMonth}</span> {end.year}
+ {endMonthTitle}
</>
) : (
<>
- <span {...stylex.props(styles.titleEmphasis)}>{startMonth}</span>{' '}
- {start.year} -{' '}
- <span {...stylex.props(styles.titleEmphasis)}>{endMonth}</span> {end.year}
+ <LocalizedMonthTitle
+ date={start}
+ timezoneID={timezoneID}
+ locale={locale}
+ />{' '}
+ - {endMonthTitle}
</>
);
}
@@ -164,11 +198,11 @@ export function EventPill({
timezoneID?: string;
isPast?: boolean;
}) {
- const {categories} = useScheduleContext();
+ const {categories, locale} = useScheduleContext();
const category = getEventCategory(event, categories);
const timeLabel =
day != null && timezoneID != null && !isDayEvent(event)
- ? formatEventTime(event, day, timezoneID)
+ ? formatEventTime(event, day, timezoneID, locale)
: null;
return (
<span
@@ -203,11 +237,11 @@ export function MonthEventPill({
timezoneID: string;
isPast?: boolean;
}) {
- const {categories} = useScheduleContext();
+ const {categories, locale} = useScheduleContext();
const category = getEventCategory(event, categories);
const timeLabel = isDayEvent(event)
? null
- : formatEventStartTime(event, timezoneID);
+ : formatEventStartTime(event, timezoneID, locale);
return (
<span
{...stylex.props(
@@ -241,7 +275,7 @@ export function ListEventRow({
timezoneID: string;
isPast?: boolean;
}) {
- const {categories} = useScheduleContext();
+ const {categories, locale} = useScheduleContext();
const category = getEventCategory(event, categories);
return (
<div {...stylex.props(styles.listEventRow)}>
@@ -256,7 +290,7 @@ export function ListEventRow({
<span {...stylex.props(styles.listEventTime)}>
{isDayEvent(event)
? 'All day'
- : formatEventTimeRange(event, timezoneID)}
+ : formatEventTimeRange(event, timezoneID, locale)}
</span>
<span
{...stylex.props(
@@ -365,58 +399,89 @@ export function formatWithPlainDate(
date: PlainDate,
timezoneID: string,
options: Intl.DateTimeFormatOptions,
+ locale: Locale,
): string {
- return new Intl.DateTimeFormat(undefined, {
+ return new Intl.DateTimeFormat(locale, {
...options,
timeZone: timezoneID,
+ calendar: 'gregory',
}).format(new Date(plainDateToInstant(date, timezoneID, 12)));
}
-export function formatMonthTitle(date: PlainDate, timezoneID: string): string {
- return formatWithPlainDate(date, timezoneID, {
- month: 'long',
- year: 'numeric',
- });
+export function formatMonthTitle(
+ date: PlainDate,
+ timezoneID: string,
+ locale: Locale,
+): string {
+ return formatWithPlainDate(
+ date,
+ timezoneID,
+ {
+ month: 'long',
+ year: 'numeric',
+ },
+ locale,
+ );
}
export function formatWeekTitle(
start: PlainDate,
end: PlainDate,
timezoneID: string,
+ locale: Locale,
): string {
if (start.year === end.year && start.month === end.month) {
- return formatMonthTitle(start, timezoneID);
+ return formatMonthTitle(start, timezoneID, locale);
}
- const startMonth = formatWithPlainDate(start, timezoneID, {month: 'long'});
- const endMonth = formatWithPlainDate(end, timezoneID, {month: 'long'});
+ const startMonth = formatWithPlainDate(
+ start,
+ timezoneID,
+ {month: 'long'},
+ locale,
+ );
+ const endMonthTitle = formatMonthTitle(end, timezoneID, locale);
return start.year === end.year
- ? `${startMonth} - ${endMonth} ${end.year}`
- : `${startMonth} ${start.year} - ${endMonth} ${end.year}`;
+ ? `${startMonth} - ${endMonthTitle}`
+ : `${formatMonthTitle(start, timezoneID, locale)} - ${endMonthTitle}`;
}
-export function formatFullDate(date: PlainDate, timezoneID: string): string {
- return formatWithPlainDate(date, timezoneID, {
- weekday: 'long',
- month: 'long',
- day: 'numeric',
- year: 'numeric',
- });
+export function formatFullDate(
+ date: PlainDate,
+ timezoneID: string,
+ locale: Locale,
+): string {
+ return formatWithPlainDate(
+ date,
+ timezoneID,
+ {
+ weekday: 'long',
+ month: 'long',
+ day: 'numeric',
+ year: 'numeric',
+ },
+ locale,
+ );
}
export function formatWeekday(
date: PlainDate,
timezoneID: string,
weekday: 'short' | 'long',
+ locale: Locale,
): string {
- return formatWithPlainDate(date, timezoneID, {weekday});
+ return formatWithPlainDate(date, timezoneID, {weekday}, locale);
}
-export function formatDayNumber(date: PlainDate, timezoneID: string): string {
- return formatWithPlainDate(date, timezoneID, {day: 'numeric'});
+export function formatDayNumber(
+ date: PlainDate,
+ timezoneID: string,
+ locale: Locale,
+): string {
+ return formatWithPlainDate(date, timezoneID, {day: 'numeric'}, locale);
}
-export function formatHour(hour: number): string {
- return new Intl.DateTimeFormat(undefined, {
+export function formatHour(hour: number, locale: Locale): string {
+ return new Intl.DateTimeFormat(locale, {
hour: 'numeric',
timeZone: 'UTC',
}).format(new Date(Date.UTC(2026, 0, 1, hour)));
@@ -425,8 +490,9 @@ export function formatHour(hour: number): string {
export function formatTimezoneAbbreviation(
date: PlainDate,
timezoneID: string,
+ locale: Locale,
): string {
- const part = new Intl.DateTimeFormat(undefined, {
+ const part = new Intl.DateTimeFormat(locale, {
timeZone: timezoneID,
timeZoneName: 'short',
})
@@ -439,8 +505,9 @@ export function formatEventTime(
event: CalendarInstantEvent,
day: PlainDate,
timezoneID: string,
+ locale: Locale,
): string {
- const formatter = new Intl.DateTimeFormat(undefined, {
+ const formatter = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: '2-digit',
timeZone: timezoneID,
@@ -453,8 +520,9 @@ export function formatEventTime(
export function formatEventTimeRange(
event: CalendarInstantEvent,
timezoneID: string,
+ locale: Locale,
): string {
- const formatter = new Intl.DateTimeFormat(undefined, {
+ const formatter = new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: '2-digit',
timeZone: timezoneID,
@@ -467,8 +535,9 @@ export function formatEventTimeRange(
export function formatEventStartTime(
event: CalendarInstantEvent,
timezoneID: string,
+ locale: Locale,
): string {
- return new Intl.DateTimeFormat(undefined, {
+ return new Intl.DateTimeFormat(locale, {
hour: 'numeric',
minute: '2-digit',
timeZone: timezoneID,
@@ -480,11 +549,12 @@ export function formatEventAccessibilityLabel(
day: PlainDate,
timezoneID: string,
categories: ReadonlyArray<ScheduleCategory>,
+ locale: Locale,
): string {
const category = getEventCategory(event, categories);
const timeLabel = isDayEvent(event)
? 'all day'
- : formatEventTime(event, day, timezoneID);
+ : formatEventTime(event, day, timezoneID, locale);
return `${event.title}, ${category.label}, ${timeLabel}`;
}