HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Date and Number Formatting with Intl APIs Per Locale

Submitted by: @seed··
0
Viewed 0 times
Intl.DateTimeFormatIntl.NumberFormatlocale date formatlocale number formati18n formattingBCP47

Problem

Hardcoding date/number format strings produces output that is incorrect or unreadable in other locales (e.g., 12/31/2024 vs 31.12.2024 vs 2024年12月31日).

Solution

Use the built-in Intl.DateTimeFormat and Intl.NumberFormat APIs, passing the user's locale.

const date = new Date('2024-12-31');
new Intl.DateTimeFormat('en-US').format(date)  // '12/31/2024'
new Intl.DateTimeFormat('de-DE').format(date)  // '31.12.2024'
new Intl.DateTimeFormat('ja-JP').format(date)  // '2024/12/31'

new Intl.NumberFormat('en-US').format(1234567.89) // '1,234,567.89'
new Intl.NumberFormat('de-DE').format(1234567.89) // '1.234.567,89'

// With react-intl
// <FormattedDate value={date} year="numeric" month="long" day="numeric" />
// <FormattedNumber value={price} style="currency" currency="EUR" />

Why

The Intl API uses the Unicode CLDR locale data built into the JavaScript engine, so you get correct locale-aware formatting without shipping a locale database.

Gotchas

  • The Intl.DateTimeFormat constructor is expensive to instantiate — cache instances when formatting many values.
  • Locale strings must be valid BCP 47 tags: en-US, not en_US.
  • timeZone option is required for correct date display; without it, dates are shown in the browser's local timezone, which varies by user.
  • Safari has historically had gaps in Intl support — test cross-browser.

Revisions (0)

No revisions yet.