Getting to know the Intl API in JavaScript

bnevilleoneill

Brian Neville-O'Neill

Posted on June 7, 2020

Getting to know the Intl API in JavaScript

Written by Gbolahan Olagunju✏️

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 momentjs, luxon, date-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 utils function 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.

LogRocket Free Trial Banner

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
Enter fullscreen mode Exit fullscreen mode

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.DateTimeFormat constructor 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"
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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.


LogRocket: Debug JavaScript errors easier by understanding the context

Debugging code is always a tedious task. But the more you understand your errors the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to find out exavtly what the user did that led to an error.

LogRocket records console logs, page load times, stacktraces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier.

Try it for free.


The post Getting to know the Intl API in JavaScript appeared first on LogRocket Blog.

💖 💪 🙅 🚩
bnevilleoneill
Brian Neville-O'Neill

Posted on June 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related