Clean Markup

Zero-Dependency Date and Number Formatting with the JavaScript Intl API

Zero-Dependency Date and Number Formatting with the JavaScript Intl API

Historically, localizing timestamps, currency amounts, and relative times ("3 hours ago") required shipping bloated JavaScript libraries like Moment.js into the client bundle. These libraries added hundreds of kilobytes of parsing code and translation tables.

The ECMAScript Internationalization API (Intl) is built into all modern JavaScript runtimes, providing native formatting algorithms directly backed by the browser and operating system.

Example

Formatting monetary amounts and dates according to user locale preferences:

// Native currency formatting
const amount = 14250.5;

const eurFormatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR'
});
console.log(eurFormatter.format(amount)); // "14.250,50 €"

const usdFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD'
});
console.log(usdFormatter.format(amount)); // "$14,250.50"

Implementation

Formatting relative time intervals natively with Intl.RelativeTimeFormat:

const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

console.log(rtf.format(-1, 'day'));   // "yesterday"
console.log(rtf.format(2, 'hour'));   // "in 2 hours"
console.log(rtf.format(-5, 'minute')); // "5 minutes ago"

Main Point: The native Intl API delivers fast, zero-bundle-size internationalization for currencies, relative dates, and lists directly in the browser.

Credits

Photo by Fumikazu Sato on Unsplash

← Home