Getting to know the Intl API in JavaScript
Tags: javascript
Published: 2020-06-07 18:38:36

---
title: Getting to know the Intl API in JavaScript
published: true
date: 2020-05-19 15:39:13 UTC
tags: javascript
canonical_url: https://blog.logrocket.com/getting-to-know-the-intl-api-in-javascript/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/vs5gpeht162og6vxicxh.png
---
**Written by [Gbolahan Olagunju](https://blog.logrocket.com/author/iamgbols/)**✏️

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](https://momentjs.com/), [luxon](https://moment.github.io/luxon/index.html), [date-fns](https://date-fns.org/), 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl), 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](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

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

```jsx
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.DateTimeFormat` constructor receives is the locale parameter.

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

```jsx
// 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument) language tag. It is separated by hyphens with some optional and compulsory parts, e.g.:

```jsx
"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:

```jsx
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) 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:

```jsx
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:

```jsx
//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.

```jsx
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.

```jsx
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.

* * *
## [LogRocket](https://logrocket.com/signup/): 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](https://logrocket.com/signup/) 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. 

![](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/06/reproduce-javascript-errors.gif?ssl=1)

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.](https://logrocket.com/signup/) 
* * *

The post [Getting to know the Intl API in JavaScript](https://blog.logrocket.com/getting-to-know-the-intl-api-in-javascript/) appeared first on [LogRocket Blog](https://blog.logrocket.com).