Chris Cooper
GitHubLinkedIn

JavaScript Internationalization API

  • javascript

Here are some cool uses of the JavaScript Intl API.

Formatting Dates

const date = new Date(Date.now());

new Intl.DateTimeFormat("en-US", {
timeZone: "America/Los_Angeles",
minute: "numeric",
hour: "numeric",
}).format(date);

// 9:45 AM (returns the current time in that timeZone)

Formatting Numbers

In the US the spelling "liter" is used whereas in the UK "litre" is used.

new Intl.NumberFormat("en-GB", {
style: "unit",
unit: "liter",
unitDisplay: "long",
}).format(1); // '1 litre'

Formatting Lists

const list = ["Motorcycle", "Bus", "Car"];

new Intl.ListFormat(
"en-US",
{ style: "long", type: "conjunction" }
).format(list); // 'Motorcycle, Bus, and Car'

Language Sensitive String Comparison

['Z', 'a', 'z', 'รค'].sort();
// Expected output: Array ['Z', 'a', 'z', 'รค']

['Z', 'a', 'z', 'รค'].sort(new Intl.Collator('de').compare);
// Expected output: Array ["a", "รค", "z", "Z"]