snippetjavascriptTippending
JavaScript Intl API for formatting dates, numbers, and strings
Viewed 0 times
IntlDateTimeFormatNumberFormatlocalei18nformatting
Problem
Formatting dates, numbers, and currencies correctly for different locales without pulling in heavy libraries like moment.js.
Solution
Use the built-in Intl API:
// Date formatting
const date = new Date();
new Intl.DateTimeFormat('en-US').format(date); // '3/1/2026'
new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', day: 'numeric'
}).format(date); // 'March 1, 2026'
// Relative time
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day'); // 'yesterday'
rtf.format(3, 'hour'); // 'in 3 hours'
// Number formatting
new Intl.NumberFormat('en-US').format(1234567.89); // '1,234,567.89'
new Intl.NumberFormat('de-DE').format(1234567.89); // '1.234.567,89'
// Currency
new Intl.NumberFormat('en-US', {
style: 'currency', currency: 'USD'
}).format(42.5); // '$42.50'
// Compact notation
new Intl.NumberFormat('en', { notation: 'compact' }).format(1500000); // '1.5M'
// List formatting
new Intl.ListFormat('en', { type: 'conjunction' }).format(['a', 'b', 'c']); // 'a, b, and c'
// Pluralization
const pr = new Intl.PluralRules('en');
pr.select(0); // 'other'
pr.select(1); // 'one'
pr.select(2); // 'other'
// Date formatting
const date = new Date();
new Intl.DateTimeFormat('en-US').format(date); // '3/1/2026'
new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', day: 'numeric'
}).format(date); // 'March 1, 2026'
// Relative time
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day'); // 'yesterday'
rtf.format(3, 'hour'); // 'in 3 hours'
// Number formatting
new Intl.NumberFormat('en-US').format(1234567.89); // '1,234,567.89'
new Intl.NumberFormat('de-DE').format(1234567.89); // '1.234.567,89'
// Currency
new Intl.NumberFormat('en-US', {
style: 'currency', currency: 'USD'
}).format(42.5); // '$42.50'
// Compact notation
new Intl.NumberFormat('en', { notation: 'compact' }).format(1500000); // '1.5M'
// List formatting
new Intl.ListFormat('en', { type: 'conjunction' }).format(['a', 'b', 'c']); // 'a, b, and c'
// Pluralization
const pr = new Intl.PluralRules('en');
pr.select(0); // 'other'
pr.select(1); // 'one'
pr.select(2); // 'other'
Why
Intl is built into all modern browsers and Node.js. No library needed for locale-aware formatting.
Revisions (0)
No revisions yet.