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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...