Chapter 11. Internationalization
Introduction
Modern browsers include a robust Internationalization API. This is a collection of APIs centered around language- or locale-specific tasks, such as:
-
Formatting dates and times
-
Formatting numbers
-
Currency
-
Pluralization rules
Before this API was available, you might have had to reach for a third-party library like Moment.js (for dates and times) or Numeral.js (for numbers). However, today’s browsers support many of the same use cases, and you may not need these libraries in your app anymore.
Most of these APIs use the concept of a locale, which is usually a combination of a language and a region. For example, the locale for US English is en-US
, and the locale for Canadian English is en-CA
. You can use them with the default locale, which is the one being used by the browser, or you can specify a particular locale to format data appropriately for your desired region.
Note
There is a new JavaScript date and time API in development called Temporal. At the time of writing, this is currently an ECMAScript proposal. It may become part of the language in the near future, but for the time being this book will cover the standard Date API.
Formatting a Date
Problem
You want to display a Date
object in a format appropriate for the user’s locale.
Solution
Use Intl.DateTimeFormat
to format the Date
object to a string value. Create the format object with two arguments: the desired locale and an options object where you can specify ...
Get Web API Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.