Skip to content

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

TypeScript

fix(i18n): localize Timestamp relative formats (#5859)

nynexman44646949d4b3683f
diff --git a/.changeset/timestamp-relative-provider-locale.md b/.changeset/timestamp-relative-provider-locale.md
new file mode 100644
index 0000000000..34161c4c5d
--- /dev/null
+++ b/.changeset/timestamp-relative-provider-locale.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Timestamp relative and compact-relative labels now follow the active provider locale, including locale-specific plural rules and word order.
+
+@nynexman4464
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index 268bc697ef..a2b8d50cb7 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -14,5 +14,9 @@
{
"component": "core/Text",
"reason": "Text sets typography — size, weight, colour, line-height, wrapping, truncation — and nothing else. Its one alignment prop is `justify`, which compiles to the logical `text-align: start | center | end` and defaults to `start`, so text hangs off the correct edge in either direction without a component-side branch. Truncation is `text-overflow: ellipsis` and `-webkit-line-clamp`, both of which put the ellipsis at the reading end on their own, and the tooltip that accompanies a clamped string is placed with the logical `above`/`below`/`start`/`end` vocabulary. Nothing is positioned, nothing is transformed, and the component renders no glyph, separator, or control."
+ },
+ {
+ "component": "core/Timestamp",
+ "reason": "Timestamp renders locale-formatted text and a direction-neutral hover card; it has no directional icons, contextual decorations, side-specific layout, order, scroll, drag, or directional keyboard behavior."
}
]
diff --git a/apps/storybook/stories/Timestamp.stories.tsx b/apps/storybook/stories/Timestamp.stories.tsx
index 7c5f8e26e0..06dad8b2f9 100644
--- a/apps/storybook/stories/Timestamp.stories.tsx
+++ b/apps/storybook/stories/Timestamp.stories.tsx
@@ -2,6 +2,7 @@
import type {Meta, StoryObj} from '@storybook/react';
import {Timestamp} from '@astryxdesign/core/Timestamp';
+import {InternationalizationProvider} from '@astryxdesign/core/i18n';
import {Text} from '@astryxdesign/core/Text';
const meta: Meta<typeof Timestamp> = {
@@ -144,6 +145,66 @@ export const RelativeShortFormat: Story = {
),
};
+const relativeThresholds = [
+ {label: 'Present clamp · 5 seconds ago', offsetSeconds: -5},
+ {label: 'Past seconds begin · 10 seconds ago', offsetSeconds: -10},
+ {label: 'Past minutes begin · 60 seconds ago', offsetSeconds: -60},
+ {label: 'Past hours begin · 1 hour ago', offsetSeconds: -3600},
+ {label: 'Past days begin · 1 day ago', offsetSeconds: -86400},
+ {label: 'Past months begin · 30 days ago', offsetSeconds: -30 * 86400},
+ {label: 'Past years begin · 365 days ago', offsetSeconds: -365 * 86400},
+ {label: 'Future skew clamp · 30 seconds', offsetSeconds: 30},
+ {label: 'Future seconds begin · 31 seconds', offsetSeconds: 31},
+ {label: 'Future minutes begin · 60 seconds', offsetSeconds: 60},
+ {label: 'Future hours begin · 1 hour', offsetSeconds: 3600},
+ {label: 'Future days begin · 1 day', offsetSeconds: 86400},
+ {label: 'Future months begin · 30 days', offsetSeconds: 30 * 86400},
+ {label: 'Future years begin · 365 days', offsetSeconds: 365 * 86400},
+] as const;
+
+function RelativeThresholds({locale}: {locale: string}) {
+ const now = Date.now() / 1000;
+ return (
+ <InternationalizationProvider locale={locale}>
+ <div style={{width: 680}}>
+ <Text type="large" weight="bold">
+ Relative-time transition points
+ </Text>
+ <Text type="supporting" color="secondary" display="block">
+ Provider locale: {locale}
+ </Text>
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: 'minmax(280px, 1fr) minmax(160px, auto)',
+ gap: '10px 32px',
+ marginTop: 20,
+ }}>
+ {relativeThresholds.map(({label, offsetSeconds}) => (
+ <div key={label} style={{display: 'contents'}}>
+ <Text type="supporting" color="secondary">
+ {label}
+ </Text>
+ <Timestamp
+ value={now + offsetSeconds}
+ format="relative"
+ hasTooltip={false}
+ type="body"
+ color="primary"
+ />
+ </div>
+ ))}
+ </div>
+ </div>
+ </InternationalizationProvider>
+ );
+}
+
+export const RelativeThresholdsEnglish: Story = {
+ name: 'Relative thresholds · English',
+ render: () => <RelativeThresholds locale="en-US" />,
+};
+
export const DateFormat: Story = {
args: {
value: '2026-02-19T17:00:00Z',
diff --git a/internal/eslint-plugin-astryx/README.md b/internal/eslint-plugin-astryx/README.md
index 398bac97fc..04c7f3dc1d 100644
--- a/internal/eslint-plugin-astryx/README.md
+++ b/internal/eslint-plugin-astryx/README.md
@@ -70,8 +70,9 @@ Approved implementations:
- `packages/core/src/utils/plainDate.ts`, `.../utils/dateParser.ts` — date
formatting/parsing core
- `packages/core/src/Timestamp/formatInstant.ts`,
- `.../Timestamp/tooltipEntries.ts` — Timestamp formatting and its
- non-display time-zone validity probe
+ `.../Timestamp/formatRelativeTime.ts`, `.../Timestamp/tooltipEntries.ts` —
+ Timestamp absolute/relative formatting and its non-display time-zone validity
+ probe
- `packages/core/src/PowerSearch/formatFilterValue.ts`
- `packages/core/src/NumberInput/numberParser.ts` — reads typed and pasted
numbers under the field's locale
diff --git a/internal/eslint-plugin-astryx/no-raw-intl-locale.js b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
index 611cd7d09a..cb8f348205 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.js
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.js
@@ -13,7 +13,8 @@
* Shipped component code must read it through the public provider-aware
* locale utilities (`useLocale()`, `useCollator()` from
* `@astryxdesign/core/i18n`, or an existing formatting helper such as
- * `plainDateFormat`/`formatInstant`/`formatFilterValue`) — never construct an
+ * `plainDateFormat`/`formatInstant`/`formatRelativeTime`/`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.
@@ -106,9 +107,10 @@ const APPROVED_IMPLEMENTATION_FILES = [
// 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
- // (the latter's fixed en-US locale only probes identifier validity).
+ // Timestamp's absolute/relative formatters and tooltip zone resolution (the
+ // latter's fixed en-US locale only probes identifier validity).
'packages/core/src/Timestamp/formatInstant.ts',
+ 'packages/core/src/Timestamp/formatRelativeTime.ts',
'packages/core/src/Timestamp/tooltipEntries.ts',
'packages/core/src/PowerSearch/formatFilterValue.ts',
// NumberInput's locale-aware read of typed and pasted text: it derives the
@@ -473,7 +475,8 @@ const rule = {
'Do not call Intl directly. Use a public provider-aware locale ' +
'utility instead (useLocale()/useCollator() from ' +
'@astryxdesign/core/i18n, or an existing formatting helper such as ' +
- 'plainDateFormat/formatInstant/formatFilterValue) so the locale ' +
+ 'plainDateFormat/formatInstant/formatRelativeTime/formatFilterValue) ' +
+ 'so the locale ' +
'always traces back to InternationalizationProvider. An explicit ' +
'locale argument does not satisfy this rule — literals, variables, ' +
'and navigator.language are all still raw Intl access here. Raw ' +
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 efcacffb4a..c66226a5e1 100644
--- a/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
+++ b/internal/eslint-plugin-astryx/no-raw-intl-locale.test.mjs
@@ -34,6 +34,8 @@ const COMPONENT_FILE = 'packages/core/src/Calendar/Calendar.tsx';
const INFRA_FILE = 'packages/core/src/utils/plainDate.ts';
const DATE_PARSER_INFRA_FILE = 'packages/core/src/utils/dateParser.ts';
const COLLATOR_INFRA_FILE = 'packages/core/src/i18n/useCollator.ts';
+const RELATIVE_TIME_INFRA_FILE =
+ 'packages/core/src/Timestamp/formatRelativeTime.ts';
const NUMBER_PARSER_INFRA_FILE =
'packages/core/src/NumberInput/numberParser.ts';
const NUMBER_PARSER_TEST_ORACLE_FILE =
@@ -128,6 +130,10 @@ tester.run('no-raw-intl-locale', rule, {
code: `new Intl.Collator(locale, options);`,
filename: COLLATOR_INFRA_FILE,
},
+ {
+ code: `new Intl.RelativeTimeFormat(locale, {style: 'narrow'});`,
+ filename: RELATIVE_TIME_INFRA_FILE,
+ },
{
code: `new Intl.NumberFormat(locale).formatToParts(12345.6);`,
filename: NUMBER_PARSER_INFRA_FILE,
@@ -264,6 +270,11 @@ tester.run('no-raw-intl-locale', rule, {
filename: NUMBER_PARSER_INFRA_FILE,
errors: [ambientIntlInImplementation],
},
+ {
+ code: `new Intl.RelativeTimeFormat();`,
+ filename: RELATIVE_TIME_INFRA_FILE,
+ errors: [ambientIntlInImplementation],
+ },
{
code: `value.toLocaleString();`,
filename: CHARTS_INFRA_FILE,
diff --git a/packages/core/src/Timestamp/Timestamp.doc.mjs b/packages/core/src/Timestamp/Timestamp.doc.mjs
index b0ba4f2f4a..9a17832c0e 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' shows '2 hours ago', 'relative_short' shows the same tiers abbreviated ('2h ago', '1d ago', '3mo ago') 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.",
+ "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.",
default: "'auto'",
},
{
@@ -186,7 +186,7 @@ export const docsDense = {
},
propDescriptions: {
value: 'date/time as unix seconds or ISO string',
- format: "display mode: 'relative', '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'",
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 7f190a1ce7..e9d722b46e 100644
--- a/packages/core/src/Timestamp/Timestamp.test.tsx
+++ b/packages/core/src/Timestamp/Timestamp.test.tsx
@@ -256,6 +256,65 @@ describe('Timestamp', () => {
});
});
+ it.each([
+ {format: 'relative' as const, style: 'long' as const},
+ {format: 'relative_short' as const, style: 'narrow' as const},
+ {format: 'auto' as const, style: 'long' as const},
+ ])(
+ 'updates $format output when the provider locale changes',
+ ({format, style}) => {
+ const value = Date.now() / 1000 - 2 * 3600;
+ const timestamp = (locale: string) => (
+ <InternationalizationProvider locale={locale}>
+ <Timestamp
+ value={value}
+ format={format}
+ hasTooltip={false}
+ data-testid="ts"
+ />
+ </InternationalizationProvider>
+ );
+ const expected = (locale: string) =>
+ new Intl.RelativeTimeFormat(locale, {
+ numeric: 'always',
+ style,
+ }).format(-2, 'hour');
+
+ const {rerender} = render(timestamp('en-US'));
+ expect(screen.getByTestId('ts')).toHaveTextContent(expected('en-US'));
+
+ rerender(timestamp('fr-FR'));
+ expect(screen.getByTestId('ts')).toHaveTextContent(expected('fr-FR'));
+ },
+ );
+
+ it('localizes relative idioms from the provider locale', () => {
+ const timestamp = (value: number) => (
+ <InternationalizationProvider locale="fr-FR">
+ <Timestamp
+ value={value}
+ format="relative"
+ hasTooltip={false}
+ data-testid="ts"
+ />
+ </InternationalizationProvider>
+ );
+ const formatter = new Intl.RelativeTimeFormat('fr-FR', {
+ numeric: 'auto',
+ style: 'long',
+ });
+
+ const {rerender} = render(timestamp(Date.now() / 1000 - 5));
+ expect(screen.getByTestId('ts')).toHaveTextContent(
+ formatter.format(0, 'second'),
+ );
+
+ rerender(timestamp(Date.now() / 1000 - 100000));
+ expect(screen.getByTestId('ts')).toHaveTextContent(
+ formatter.format(-1, 'day'),
+ );
+ });
+
// --- Standard display formats ---
it('updates absolute output when the provider locale changes', () => {
@@ -596,11 +655,24 @@ describe('Timestamp', () => {
expect(screen.getByText('now')).toBeInTheDocument();
});
- it('renders a genuine near-future time beyond the skew tolerance', () => {
+ it('renders a genuine near-future time beyond the skew tolerance with the native formatter', () => {
// Past the skew window — this is a real upcoming time, not clock drift.
const fortyFiveSecondsFromNow = Date.now() / 1000 + 45;
- render(<Timestamp value={fortyFiveSecondsFromNow} format="relative" />);
- expect(screen.getByText('in a few seconds')).toBeInTheDocument();
+ render(
+ <Timestamp
+ value={fortyFiveSecondsFromNow}
+ format="relative"
+ hasTooltip={false}
+ />,
+ );
+ expect(
+ screen.getByText(
+ new Intl.RelativeTimeFormat('en', {
+ numeric: 'always',
+ style: 'long',
+ }).format(45, 'second'),
+ ),
+ ).toBeInTheDocument();
});
// --- Long-ago relative ---
diff --git a/packages/core/src/Timestamp/Timestamp.tsx b/packages/core/src/Timestamp/Timestamp.tsx
index 85e2c1df25..0e9fc46315 100644
--- a/packages/core/src/Timestamp/Timestamp.tsx
+++ b/packages/core/src/Timestamp/Timestamp.tsx
@@ -4,11 +4,12 @@
/**
* @file Timestamp.tsx
- * @input Uses React, Intl.DateTimeFormat, Text
+ * @input Uses React, Text, provider locale, and Timestamp formatters
* @output Exports Timestamp component and related types
* @position Core implementation; renders formatted timestamps
*
* SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Timestamp/formatRelativeTime.ts
* - /packages/core/src/Timestamp/Timestamp.doc.mjs
* - /packages/core/src/Timestamp/Timestamp.test.tsx
* - /packages/core/src/Timestamp/index.ts
@@ -27,6 +28,7 @@ import {useLocale} from '../i18n/useLocale';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {formatInstant} from './formatInstant';
+import {formatRelativeTime} from './formatRelativeTime';
import {formatTooltipLines} from './tooltipEntries';
import type {
TimestampTooltipEntry,
@@ -65,8 +67,8 @@ export interface TimestampProps extends BaseProps<HTMLTimeElement> {
/**
* Display format.
* - `'relative'`: "2 hours ago", "yesterday", "now"
- * - `'relative_short'`: "2h ago", "1d ago", "now" — the same tiers as
- * `'relative'` with abbreviated units (s/m/h/d/mo/y), for compact,
+ * - `'relative_short'`: "2h ago", "1d ago", "now" in English — the
+ * locale's native narrow relative-time pattern, for compact,
* space-constrained surfaces
* - `'auto'`: Relative for recent times, `date_time` for older
* - `'date'`: "Mar 21, 2025"
@@ -185,24 +187,10 @@ const styles = stylex.create({
const MINUTE = 60;
const HOUR = 3600;
const DAY = 86400;
-const MONTH = 30 * DAY;
-const YEAR = 365 * DAY;
/** Default auto threshold: 7 days in seconds */
const DEFAULT_AUTO_THRESHOLD = 7 * DAY;
-/**
- * Tolerance (in seconds) for treating a *future* timestamp as the present.
- * A value only a handful of seconds ahead of our reference clock is almost
- * always clock skew — the displayed `now` lagging the real clock, or the value
- * being produced on a slightly faster clock — not a genuine future event, so
- * it reads as "now" rather than a confusing "in a few seconds". The future
- * side gets a wider window than the past (which only needs to absorb the
- * sub-second render-time lag) because future drift is far more likely to be
- * skew than real.
- */
-const FUTURE_SKEW_TOLERANCE = 30;
-
function parseValue(value: string | number): Date {
if (typeof value === 'number') {
// Heuristic: if the number is less than 1e12, treat as seconds; otherwise ms.
@@ -212,140 +200,6 @@ function parseValue(value: string | number): Date {
return new Date(value);
}
-function getRelativeTimeString(date: Date, now: Date): string {
- const diffSeconds = Math.round((now.getTime() - date.getTime()) / 1000);
-
- // Treat values at (or a hair before/after) the present as "now". The
- // internal `now` reference is captured at render time, so it can lag the
- // real clock; a value equal to "right now" can land a fraction of a second
- // in the future and round to a small negative delta. Without this clamp,
- // such values fall into the future branch and render "in a few seconds".
- if (Math.abs(diffSeconds) < 10) {
- return 'now';
- }
-
- if (diffSeconds < 0) {
- // Future dates
- const absDiff = Math.abs(diffSeconds);
- // A value only a few seconds ahead of our clock is almost always skew, not
- // a genuine future event — render it as the present rather than a
- // confusing "in a few seconds". Wider than the past window above on
- // purpose (see FUTURE_SKEW_TOLERANCE).
- if (absDiff <= FUTURE_SKEW_TOLERANCE) {
- return 'now';
- }
- if (absDiff < MINUTE) {
- return 'in a few seconds';
- }
- if (absDiff < HOUR) {
- const mins = Math.floor(absDiff / MINUTE);
- return `in ${mins} ${mins === 1 ? 'minute' : 'minutes'}`;
- }
- if (absDiff < DAY) {
- const hours = Math.floor(absDiff / HOUR);
- return `in ${hours} ${hours === 1 ? 'hour' : 'hours'}`;
- }
- if (absDiff < MONTH) {
- const days = Math.floor(absDiff / DAY);
- return `in ${days} ${days === 1 ? 'day' : 'days'}`;
- }
- if (absDiff < YEAR) {
- const months = Math.floor(absDiff / MONTH);
- return `in ${months} ${months === 1 ? 'month' : 'months'}`;
- }
- const years = Math.floor(absDiff / YEAR);
- return `in ${years} ${years === 1 ? 'year' : 'years'}`;
- }
-
- if (diffSeconds < MINUTE) {
- return `${diffSeconds} seconds ago`;
- }
- if (diffSeconds < HOUR) {
- const mins = Math.floor(diffSeconds / MINUTE);
- return `${mins} ${mins === 1 ? 'minute' : 'minutes'} ago`;
- }
- if (diffSeconds < DAY) {
- const hours = Math.floor(diffSeconds / HOUR);
- return `${hours} ${hours === 1 ? 'hour' : 'hours'} ago`;
- }
- if (diffSeconds < 2 * DAY) {
- return 'yesterday';
- }
- if (diffSeconds < MONTH) {
- const days = Math.floor(diffSeconds / DAY);
- return `${days} days ago`;
- }
- if (diffSeconds < YEAR) {
- const months = Math.floor(diffSeconds / MONTH);
- return `${months} ${months === 1 ? 'month' : 'months'} ago`;
- }
- const years = Math.floor(diffSeconds / YEAR);
- return `${years} ${years === 1 ? 'year' : 'years'} ago`;
-}
-
-/**
- * The compact sibling of `getRelativeTimeString`: the same tier boundaries and
- * present/future-skew handling, rendered with abbreviated units for
- * space-constrained surfaces (chat metadata, dense tables, chips).
- *
- * Units follow the common compact convention (and the Microsoft Style Guide):
- * `s` seconds, `m` minutes, `h` hours, `d` days, `mo` months, `y` years.
- * Months use `mo` — not `m` — because `m` already means minutes; a bare `m`
- * for months would be ambiguous. The value is always numeric (no "yesterday"
- * idiom, which belongs to the long form) so the short form stays predictable
- * and easy to scan. The `ago` / `in` affixes are kept so direction stays
- * unambiguous at a glance.
- */
-function getRelativeTimeShortString(date: Date, now: Date): string {
- const diffSeconds = Math.round((now.getTime() - date.getTime()) / 1000);
-
- // Present clamp — identical to the long form (see getRelativeTimeString).
- if (Math.abs(diffSeconds) < 10) {
- return 'now';
- }
-
- if (diffSeconds < 0) {
- // Future dates.
- const absDiff = Math.abs(diffSeconds);
- if (absDiff <= FUTURE_SKEW_TOLERANCE) {
- return 'now';
- }
- if (absDiff < MINUTE) {
- return `in ${absDiff}s`;
- }
- if (absDiff < HOUR) {
- return `in ${Math.floor(absDiff / MINUTE)}m`;
- }
- if (absDiff < DAY) {
- return `in ${Math.floor(absDiff / HOUR)}h`;
- }
- if (absDiff < MONTH) {
- return `in ${Math.floor(absDiff / DAY)}d`;
- }
- if (absDiff < YEAR) {
- return `in ${Math.floor(absDiff / MONTH)}mo`;
- }
- return `in ${Math.floor(absDiff / YEAR)}y`;
- }
-
- if (diffSeconds < MINUTE) {
- return `${diffSeconds}s ago`;
- }
- if (diffSeconds < HOUR) {
- return `${Math.floor(diffSeconds / MINUTE)}m ago`;
- }
- if (diffSeconds < DAY) {
- return `${Math.floor(diffSeconds / HOUR)}h ago`;
- }
- if (diffSeconds < MONTH) {
- return `${Math.floor(diffSeconds / DAY)}d ago`;
- }
- if (diffSeconds < YEAR) {
- return `${Math.floor(diffSeconds / MONTH)}mo ago`;
- }
- return `${Math.floor(diffSeconds / YEAR)}y ago`;
-}
-
/** Returns the interval (in ms) at which a relative timestamp should update. */
function getLiveInterval(diffSeconds: number): number {
const absDiff = Math.abs(diffSeconds);
@@ -449,9 +303,9 @@ export function Timestamp({
const displayText = !isValidDate
? ''
: effectiveFormat === 'relative'
- ? getRelativeTimeString(date, now)
+ ? formatRelativeTime(date, now, locale, 'long')
: effectiveFormat === 'relative_short'
- ? getRelativeTimeShortString(date, now)
+ ? formatRelativeTime(date, now, locale, 'narrow')
: isAbsoluteFormat(effectiveFormat)
? formatInstant(date, effectiveFormat, locale, {isTimezoneShown})
: '';
diff --git a/packages/core/src/Timestamp/formatRelativeTime.ts b/packages/core/src/Timestamp/formatRelativeTime.ts
new file mode 100644
index 0000000000..e9c3e21dbd
--- /dev/null
+++ b/packages/core/src/Timestamp/formatRelativeTime.ts
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file formatRelativeTime.ts
+ * @input A Date, reference Date, provider locale, and long or narrow style
+ * @output A locale-correct relative time string
+ * @position Pure locale-aware formatting boundary for Timestamp's relative modes
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Timestamp/Timestamp.tsx
+ * - /packages/core/src/Timestamp/Timestamp.test.tsx
+ * - /packages/core/src/Timestamp/Timestamp.doc.mjs
+ */
+
+import type {Locale} from '../i18n/types';
+
+const MINUTE = 60;
+const HOUR = 3600;
+const DAY = 86400;
+const MONTH = 30 * DAY;
+const YEAR = 365 * DAY;
+
+/**
+ * Tolerance for treating a future timestamp as the present. Values this close
+ * are usually clock skew rather than a genuinely scheduled future instant.
+ */
+const FUTURE_SKEW_TOLERANCE = 30;
+
+type RelativeTimeStyle = 'long' | 'narrow';
+type RelativeTimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'month' | 'year';
+
+const formatters = new Map<string, Intl.RelativeTimeFormat>();
+
+function getFormatter(
+ locale: Locale,
+ style: RelativeTimeStyle,
+ numeric: Intl.RelativeTimeFormatNumeric,
+): Intl.RelativeTimeFormat {
+ const key = JSON.stringify([locale, style, numeric]);
+ let formatter = formatters.get(key);
+ if (formatter == null) {
+ formatter = new Intl.RelativeTimeFormat(locale, {numeric, style});
+ formatters.set(key, formatter);
+ }
+ return formatter;
+}
+
+/**
+ * Chooses Astryx's existing time tier, then delegates locale-specific wording,
+ * plural rules, and word order to the platform's CLDR-backed formatter.
+ */
+export function formatRelativeTime(
+ date: Date,
+ now: Date,
+ locale: Locale,
+ style: RelativeTimeStyle,
+): string {
+ const diffSeconds = Math.round((now.getTime() - date.getTime()) / 1000);
+ const absDiff = Math.abs(diffSeconds);
+
+ // Treat values at (or a hair before/after) the present as "now". The wider
+ // future tolerance absorbs realistic clock skew.
+ if (absDiff < 10 || (diffSeconds < 0 && absDiff <= FUTURE_SKEW_TOLERANCE)) {
+ return getFormatter(locale, style, 'auto').format(0, 'second');
+ }
+
+ let count: number;
+ let unit: RelativeTimeUnit;
+ if (absDiff < MINUTE) {
+ count = absDiff;
+ unit = 'second';
+ } else if (absDiff < HOUR) {
+ count = Math.floor(absDiff / MINUTE);
+ unit = 'minute';
+ } else if (absDiff < DAY) {
+ count = Math.floor(absDiff / HOUR);
+ unit = 'hour';
+ } else if (absDiff < MONTH) {
+ count = Math.floor(absDiff / DAY);
+ unit = 'day';
+ } else if (absDiff < YEAR) {
+ count = Math.floor(absDiff / MONTH);
+ unit = 'month';
+ } else {
+ count = Math.floor(absDiff / YEAR);
+ unit = 'year';
+ }
+
+ // Intl uses positive values for the future and negative values for the past.
+ const value = diffSeconds < 0 ? count : -count;
+ // Preserve the long form's existing "yesterday" idiom. The compact form is
+ // deliberately numeric, so English remains "1d ago" rather than "yesterday".
+ const numeric =
+ style === 'long' && unit === 'day' && value === -1 ? 'auto' : 'always';
+ return getFormatter(locale, style, numeric).format(value, unit);
+}