Skip to main content

Getting to know the Intl API in JavaScript

The JavaScript logo against a yellow background.

As an application begins to increase in adoption, it becomes important to personalize user experience across different timezone and localities.

In the past, the comprehensive solution to achieving this has been with a few libraries such as momentjsluxondate-fns, and others.

The Javascript Intl API recently gained a few additions that make it worthy of mention as an option for customizing user experience.

The Intl API also has a constructor that adds some special formatting. Previously, that would have been done with a utilsfunction when joining an array of strings.

According to MDN, the Intl object is the namespace for the ECMAScript Internationalization API and provides language-sensitive string comparisons, number formatting, and date and time formatting.

The Intl object provides access to several constructors as well as functionality common to the internationalization constructors and other language-sensitive functions.

Enough theory — let’s see some examples of how this actually works:

const date = new Date();
const locale = "en-US"
const engUsFormat = new Intl.DateTimeFormat(locale).format(date);
console.log(engUsFormat); // 4/23/2020

With just a few lines of code, we have a localized date.

All this could have been done in a single line of code, but I broke this down for the sake of emphasis and ease of understanding.

We have a variable called engUsFormat that we can reuse across our application without having to repeat ourselves.

A very important argument that the Intl.DateTimeFormatconstructor receives is the locale parameter.

Ideally, we will want to get this dynamically depending on where our applications is being accessed:

// this result will vary depending on your location and user setting preference.
const locale = navigator.language
console.log(locale); // "en-US"

The Locale in focus

NB: You don’t need a more in-depth understanding into the locale option to follow along with the rest of this article or to use the Intl object.

However, if you want to know how this works under the hood feel free to read along.

A locale is a string that represents a set of user preferences, including but not limited to the following:

  • Date and Time (i.e .,should we display dates using an Arabic or Chinese calendar)
  • Numbers and currency (i.e., should we use Roman numerals or digits, pounds, or dollars)
  • Timezones, languages, and countries
  • Measurement units (i.e., kg or lbs, etc.)

The locale argument must be a string in the BCP 47 language tag. It is separated by hyphens with some optional and compulsory parts, e.g.:

"en-US" // only the en is compulsory the US is additional information that helps customization
"ja-JP-u-ca-japanese" // only the ja is compulsory.

So far, we have seen a glimpse of the Intl global object. However, there are a few constructors that have been added to the namespace that are worth mentioning:

  • DateTimeFormat
  • NumberFormat
  • Collator
  • ListFormat
  • PluralRules
  • RelativeTimeFormat

We will be exploring some of the above in detail and see possible use cases for these in our applications.

The intl also has the options argument that gives us great flexibility:

const options = {
year: "2-digit",
month: "short",
day: "2-digit",
hour: "numeric",
minute: "numeric",
weekday: "long",
hour12: true,
};

console.log(new Intl.DateTimeFormat("en-US", options).format(new Date()));
"Saturday, Apr 25, 20, 5:44 PM"

This guide at MDN provides a thorough list of the possible options.

NumberFormat

We can use this constructor to format number by presenting it in a readable format and format currencies by providing the options argument:

console.log(new Intl.NumberFormat("en-Us").format(1234567890));
"1,234,567,890"
console.log(new Intl.NumberFormat("de-DE").format(1234567890));
"1.234.567.890"

For Formatting currencies:

//for the American Dollar
new Intl.NumberFormat("en-Us", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2
}).format(7654);
"$7,654.00"

//for the British Pounds
new Intl.NumberFormat("en-Us", {
style: "currency",
currency: "GBP",
minimumFractionDigits: 2
}).format(7654);
"£7,654.00"

RelativeTimeFormat

This constructor is used to convert date and time into a user-friendly and readable format.

This is one of the very nice features that was previously exclusive to momentjs.

NB: This feature isn’t supported by all browsers yet.

const relativeTimeFormat = new Intl.RelativeTimeFormat("en-US");
relativeTimeFormat.format(10, 'seconds');
"in 10 seconds"
relativeTimeFormat.format(-10, 'seconds');
"10 seconds ago"
relativeTimeFormat.format(-5, 'month');
"5 months ago"
relativeTimeFormat.format(3, 'year');
"in 3 years"

ListFormat

This constructor is used for joining an array of strings with either a conjunction or a disjunction to form a meaningful phrase. It defaults to a conjunction when no type is supplied.

const listFormat = new Intl.ListFormat("en-US");
listFormat.format(['Dafe', 'Daneil', "Gbolahan", "Kelani", "David"]);
"Dafe, Daneil, Gbolahan, Kelani, and David"

const listFormatOr = new Intl.ListFormat("en-US", {type: 'disjunction'});
listFormatOr.format(["Beans", "Rice", "Plantian"])
"Beans, Rice, or Plantian"

Conclusion

Often times, there is no need to use an external library when formatting dates and timezones according to user preferences if we take advantage of the built-in Intl global object.

It saves our application a few extra bytes of JavaScript to parse and reduce size and load time.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...