Intl.PluralRules - JavaScript

Intl.PluralRules
================

The **`Intl.PluralRules`** object enables plural-sensitive formatting and plural-related language rules.

Description
-----------

 Languages use different patterns for expressing both plural numbers of items (cardinal numbers) and for expressing the order of items (ordinal numbers).
 English has two forms for expressing cardinal numbers: one for the singular "item" (1 hour, 1 dog, 1 fish) and the other for zero or any other number of "items" (0 hours, 2 lemmings, 100000.5 fish), while Chinese has only one form, and Arabic has six!
 Similarly, English has four forms for expressing ordinal numbers: "th", "st", "nd", "rd", giving the sequence: 0th, 1st, 2nd, 3rd, 4th, 5th, ..., 21st, 22nd, 23rd, 24th, 25th, and so on, while both Chinese and Arabic only have one form for ordinal numbers.

 Given a particular language and set of formatting options, the methods `Intl.PluralRules.prototype.select()` and `Intl.PluralRules.prototype.selectRange()` return a *tag* that represents the plural form of a single or a range of numbers, cardinal or ordinal.
 Code can use the returned tags to represent numbers appropriately for the given language.
 The full set of tags that might be returned are: `zero`, `one`, `two`, `few`, `many`, and `other` (the "general" plural form, also used if the language only has one form).

 As English only has two forms for cardinal numbers, the `select()` method returns only two tags: `"one"` for the singular case, and `"other"` for all other cardinal numbers.
 This allows construction of sentences that make sense in English for each case, such as: "1 dog is happy; do you want to play with it?" and "10 dogs are happy; do you want to play with them?".

 Creating appropriate sentences for each form depends on the language, and even in English may not be as simple as just adding "s" to a noun to make the plural form.
 Using the example above, we see that the form may affect:

* **Nouns**: 1 dogs/2 dogs (but not "fish" or "sheep", which have the same singular and plural form).
* **Verbs**: 1 dog *is* happy, 2 dogs *are* happy
* **Pronouns** (and other referents): Do you want to play with *it* / *them*.

Other languages have more forms, and choosing appropriate sentences can be even more complex.

`select()` can return any of four tags for ordinal numbers in English, representing each of the allowed forms: `one` for "st" numbers (1, 21, 31, ...), `two` for "nd" numbers (2, 22, 32, ...), `few` for "rd" numbers (3, 33, 43, ...), and `other` for "th" numbers (0, 4-20, etc.).
 Again, the returned tags allow appropriate formatting of strings describing an ordinal number.

 For more information about the rules and how they are used, see Plural Rules.
 For a list of the rules and how they apply for different languages, see the LDML Language Plural Rules.

Constructor
-----------

`Intl.PluralRules()`

Creates a new `Intl.PluralRules` object.

Static methods
--------------

`Intl.PluralRules.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.PluralRules.prototype` and shared by all `Intl.PluralRules` instances.

`Intl.PluralRules.prototype.constructor`

The constructor function that created the instance object. For `Intl.PluralRules` instances, the initial value is the `Intl.PluralRules` constructor.

`Intl.PluralRules.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.PluralRules"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.PluralRules.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.

`Intl.PluralRules.prototype.select()`

Returns a string indicating which plural rule to use for locale-aware formatting.

`Intl.PluralRules.prototype.selectRange()`

This method receives two values and returns a string indicating which plural rule to use for locale-aware formatting.

Examples
--------

### Using locales

This example shows some of the variations in localized plural rules for cardinal numbers.

In order to get the format for the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the constructor `locales` argument:

```js
// US English
const enCardinalRules = new Intl.PluralRules("en-US");
console.log(enCardinalRules.select(0)); // "other"
console.log(enCardinalRules.select(1)); // "one"
console.log(enCardinalRules.select(2)); // "other"
console.log(enCardinalRules.select(3)); // "other"

// Arabic
const arCardinalRules = new Intl.PluralRules("ar-EG");
console.log(arCardinalRules.select(0)); // "zero"
console.log(arCardinalRules.select(1)); // "one"
console.log(arCardinalRules.select(2)); // "two"
console.log(arCardinalRules.select(6)); // "few"
console.log(arCardinalRules.select(18)); // "many"
```

### Using options

The plural form of the specified number may also depend on constructor `options`, such as how the number is rounded, and whether it is cardinal or ordinal.

This example shows how you can set the type of rules to "ordinal", and how this affects the form for some numbers in US English.

```js
// US English - ordinal
const enOrdinalRules = new Intl.PluralRules("en-US", { type: "ordinal" });
console.log(enOrdinalRules.select(0)); // "other" (0th)
console.log(enOrdinalRules.select(1)); // "one" (1st)
console.log(enOrdinalRules.select(2)); // "two" (2nd)
console.log(enOrdinalRules.select(3)); // "few" (3rd)
console.log(enOrdinalRules.select(4)); // "other" (4th)
console.log(enOrdinalRules.select(21)); // "one" (21st)
```

### Formatting text using the returned tag

The code below extends the previous example, showing how you might use the returned tag for an ordinal number to format text in English.

```js
const enOrdinalRules = new Intl.PluralRules("en-US", { type: "ordinal" });

const suffixes = new Map([
  ["one", "st"],
  ["two", "nd"],
  ["few", "rd"],
  ["other", "th"],
]);
const formatOrdinals = (n) => {
  const rule = enOrdinalRules.select(n);
  const suffix = suffixes.get(rule);
  return `${n}${suffix}`;
};

formatOrdinals(0); // '0th'
formatOrdinals(1); // '1st'
formatOrdinals(2); // '2nd'
formatOrdinals(3); // '3rd'
formatOrdinals(4); // '4th'
formatOrdinals(11); // '11th'
formatOrdinals(21); // '21st'
formatOrdinals(42); // '42nd'
formatOrdinals(103); // '103rd'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # pluralrules-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.PluralRules` in FormatJS
* `Intl`


Intl.DurationFormat - JavaScript

Intl.DurationFormat
===================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`Intl.DurationFormat`** object enables language-sensitive duration formatting.

Constructor
-----------

`Intl.DurationFormat()`
Experimental

Creates a new `Intl.DurationFormat` object.

Static methods
--------------

`Intl.DurationFormat.supportedLocalesOf()`
Experimental

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.DurationFormat.prototype` and shared by all `Intl.DurationFormat` instances.

`Intl.DurationFormat.prototype.constructor`

The constructor function that created the instance object. For `Intl.DurationFormat` instances, the initial value is the `Intl.DurationFormat` constructor.

`Intl.DurationFormat.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.DurationFormat"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.DurationFormat.prototype.format()`
Experimental

Getter function that formats a duration according to the locale and formatting options of this `DurationFormat` object.

`Intl.DurationFormat.prototype.formatToParts()`
Experimental

Returns an `Array` of objects representing the formatted duration in parts.

`Intl.DurationFormat.prototype.resolvedOptions()`
Experimental

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples
--------

### Using Intl.DurationFormat

The examples below show how to use the `Intl.DurationFormat` object to format a duration object with various locales and styles.

```js
const duration = {
  hours: 1,
  minutes: 46,
  seconds: 40,
};

// With style set to "long" and locale "fr-FR"
new Intl.DurationFormat("fr-FR", { style: "long" }).format(duration);
// "1 heure, 46 minutes et 40 secondes"

// With style set to "short" and locale "en"
new Intl.DurationFormat("en", { style: "short" }).format(duration);
// "1 hr, 46 min and 40 sec"

// With style set to "short" and locale "pt"
new Intl.DurationFormat("pt", { style: "narrow" }).format(duration);
// "1h 46min 40s"
```

Specifications
--------------

| Specification |
| --- |
| Intl.DurationFormat # durationformat-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl`


Intl.DateTimeFormat - JavaScript

Intl.DateTimeFormat
===================

The **`Intl.DateTimeFormat`** object enables language-sensitive date and time formatting.

Try it
------

Constructor
-----------

`Intl.DateTimeFormat()`

Creates a new `Intl.DateTimeFormat` object.

Static methods
--------------

`Intl.DateTimeFormat.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.DateTimeFormat.prototype` and shared by all `Intl.DateTimeFormat` instances.

`Intl.DateTimeFormat.prototype.constructor`

The constructor function that created the instance object. For `Intl.DateTimeFormat` instances, the initial value is the `Intl.DateTimeFormat` constructor.

`Intl.DateTimeFormat.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.DateTimeFormat"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.DateTimeFormat.prototype.format()`

Getter function that formats a date according to the locale and formatting options of this `DateTimeFormat` object.

`Intl.DateTimeFormat.prototype.formatRange()`

This method receives two Dates and formats the date range in the most concise way based on the locale and options provided when instantiating `DateTimeFormat`.

`Intl.DateTimeFormat.prototype.formatRangeToParts()`

This method receives two Dates and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.

`Intl.DateTimeFormat.prototype.formatToParts()`

Returns an `Array` of objects representing the date string in parts that can be used for custom locale-aware formatting.

`Intl.DateTimeFormat.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples
--------

### Using DateTimeFormat

In basic use without specifying a locale, `DateTimeFormat` uses the default locale and default options.

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los\_Angeles (UTC-0800)
```

### Using locales

This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// Results below use the time zone of America/Los\_Angeles (UTC-0800, Pacific Standard Time)

// US English uses month-day-year order
console.log(new Intl.DateTimeFormat("en-US").format(date));
// "12/19/2012"

// British English uses day-month-year order
console.log(new Intl.DateTimeFormat("en-GB").format(date));
// "19/12/2012"

// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat("ko-KR").format(date));
// "2012. 12. 19."

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat("ar-EG").format(date));
// "١٩/١٢/٢٠١٢"

// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat("ja-JP-u-ca-japanese").format(date));
// "24/12/19"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// "19/12/2012"
```

### Using options

The date and time formats can be customized using the `options` argument:

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));

// request a weekday along with a long date
let options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
};
console.log(new Intl.DateTimeFormat("de-DE", options).format(date));
// "Donnerstag, 20. Dezember 2012"

// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "Thursday, December 20, 2012, GMT"

// sometimes you want to be more precise
options = {
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  timeZone: "Australia/Sydney",
  timeZoneName: "short",
};
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00 pm AEDT"

// sometimes you want to be very precise
options.fractionalSecondDigits = 3; //number digits for fraction-of-seconds
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00.200 pm AEDT"

// sometimes even the US needs 24-hour time
options = {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  hour12: false,
  timeZone: "America/Los\_Angeles",
};
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "12/19/2012, 19:00:00"

// to specify options but use the browser's default locale, use undefined
console.log(new Intl.DateTimeFormat(undefined, options).format(date));
// "12/19/2012, 19:00:00"

// sometimes it's helpful to include the period of the day
options = { hour: "numeric", dayPeriod: "short" };
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// 10 at night
```

The used calendar and numbering formats can also be set independently via `options` arguments:

```js
const options = { calendar: "chinese", numberingSystem: "arab" };
const dateFormat = new Intl.DateTimeFormat(undefined, options);
const usedOptions = dateFormat.resolvedOptions();

console.log(usedOptions.calendar);
// "chinese"

console.log(usedOptions.numberingSystem);
// "arab"

console.log(usedOptions.timeZone);
// "America/New\_York" (the users default timezone)
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # datetimeformat-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.DateTimeFormat` in FormatJS
* `Intl`


Intl.NumberFormat - JavaScript

Intl.NumberFormat
=================

The **`Intl.NumberFormat`** object enables language-sensitive number formatting.

Try it
------

Constructor
-----------

`Intl.NumberFormat()`

Creates a new `NumberFormat` object.

Static methods
--------------

`Intl.NumberFormat.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.NumberFormat.prototype` and shared by all `Intl.NumberFormat` instances.

`Intl.NumberFormat.prototype.constructor`

The constructor function that created the instance object. For `Intl.NumberFormat` instances, the initial value is the `Intl.NumberFormat` constructor.

`Intl.NumberFormat.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.NumberFormat"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.NumberFormat.prototype.format()`

Getter function that formats a number according to the locale and formatting options of this `Intl.NumberFormat` object.

`Intl.NumberFormat.prototype.formatRange()`

Getter function that formats a range of numbers according to the locale and formatting options of the `Intl.NumberFormat` object from which the method is called.

`Intl.NumberFormat.prototype.formatRangeToParts()`

Returns an `Array` of objects representing the range of number strings in parts that can be used for custom locale-aware formatting.

`Intl.NumberFormat.prototype.formatToParts()`

Returns an `Array` of objects representing the number string in parts that can be used for custom locale-aware formatting.

`Intl.NumberFormat.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.

Examples
--------

### Basic usage

In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.

```js
const number = 3500;

console.log(new Intl.NumberFormat().format(number));
// '3,500' if in US English locale
```

### Using locales

This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:

```js
const number = 123456.789;

// German uses comma as decimal separator and period for thousands
console.log(new Intl.NumberFormat("de-DE").format(number));
// 123.456,789

// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.NumberFormat("ar-EG").format(number));
// ١٢٣٤٥٦٫٧٨٩

// India uses thousands/lakh/crore separators
console.log(new Intl.NumberFormat("en-IN").format(number));
// 1,23,456.789

// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(new Intl.NumberFormat("zh-Hans-CN-u-nu-hanidec").format(number));
// 一二三,四五六.七八九

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.NumberFormat(["ban", "id"]).format(number));
// 123.456,789
```

### Using options

The results can be customized using the `options` argument:

```js
const number = 123456.789;

// request a currency format
console.log(
  new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(
    number,
  ),
);
// 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(
  new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format(
    number,
  ),
);
// ￥123,457

// limit to three significant digits
console.log(
  new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format(
    number,
  ),
);
// 1,23,000

// Formatting with units
console.log(
  new Intl.NumberFormat("pt-PT", {
    style: "unit",
    unit: "kilometer-per-hour",
  }).format(50),
);
// 50 km/h

console.log(
  (16).toLocaleString("en-GB", {
    style: "unit",
    unit: "liter",
    unitDisplay: "long",
  }),
);
// 16 litres
```

For an exhaustive list of options, see the `Intl.NumberFormat()` constructor page.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # numberformat-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.NumberFormat` in FormatJS
* `Intl`


Intl.Segmenter - JavaScript

Intl.Segmenter
==============

The **`Intl.Segmenter`** object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.

Try it
------

Constructor
-----------

`Intl.Segmenter()`

Creates a new `Intl.Segmenter` object.

Static methods
--------------

`Intl.Segmenter.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.Segmenter.prototype` and shared by all `Intl.Segmenter` instances.

`Intl.Segmenter.prototype.constructor`

The constructor function that created the instance object. For `Intl.Segmenter` instances, the initial value is the `Intl.Segmenter` constructor.

`Intl.Segmenter.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.Segmenter"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.Segmenter.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and granularity options computed during initialization of this `Intl.Segmenter` object.

`Intl.Segmenter.prototype.segment()`

Returns a new iterable `Segments` instance representing the segments of a string according to the locale and granularity of this `Intl.Segmenter` instance.

Examples
--------

### Basic usage and difference from String.prototype.split()

If we were to use `String.prototype.split(" ")` to segment a text in words, we would not get the correct result if the locale of the text does not use whitespaces between words (which is the case for Japanese, Chinese, Thai, Lao, Khmer, Myanmar, etc.).

```js
const str = "吾輩は猫である。名前はたぬき。";
console.table(str.split(" "));
// ['吾輩は猫である。名前はたぬき。']
// The two sentences are not correctly segmented.
```

```js
const str = "吾輩は猫である。名前はたぬき。";
const segmenterJa = new Intl.Segmenter("ja-JP", { granularity: "word" });

const segments = segmenterJa.segment(str);
console.table(Array.from(segments));
// [{segment: '吾輩', index: 0, input: '吾輩は猫である。名前はたぬき。', isWordLike: true},
// etc.
// ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # segmenter-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Intl.getCanonicalLocales() - JavaScript

Intl.getCanonicalLocales()
==========================

 The **`Intl.getCanonicalLocales()`** static method returns an array
 containing the canonical locale names. Duplicates will be omitted and elements will be
 validated as structurally valid language tags.

Try it
------

Syntax
------

```js
Intl.getCanonicalLocales(locales)
```

### Parameters

`locales`

A list of `String` values for which to get the canonical locale names.

### Return value

An array containing the canonical locale names.

Examples
--------

### Using getCanonicalLocales

```js
Intl.getCanonicalLocales("EN-US"); // ["en-US"]
Intl.getCanonicalLocales(["EN-US", "Fr"]); // ["en-US", "fr"]

Intl.getCanonicalLocales("EN\_US");
// RangeError:'EN\_US' is not a structurally valid language tag
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.getcanonicallocales |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.getCanonicalLocales` in FormatJS
* `Intl.NumberFormat.supportedLocalesOf()`
* `Intl.DateTimeFormat.supportedLocalesOf()`
* `Intl.Collator.supportedLocalesOf()`


Intl.Collator - JavaScript

Intl.Collator
=============

The **`Intl.Collator`** object enables language-sensitive string comparison.

Try it
------

Constructor
-----------

`Intl.Collator()`

Creates a new `Collator` object.

Static methods
--------------

`Intl.Collator.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.Collator.prototype` and shared by all `Intl.Collator` instances.

`Intl.Collator.prototype.constructor`

The constructor function that created the instance object. For `Intl.Collator` instances, the initial value is the `Intl.Collator` constructor.

`Intl.Collator.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.Collator"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.Collator.prototype.compare()`

Getter function that compares two strings according to the sort order of this `Intl.Collator` object.

`Intl.Collator.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.

Examples
--------

### Using Collator

The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:

```js
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
```

Note that the results shown in the code above can vary between browsers and browser versions. This is because the values are implementation-specific. That is, the specification requires only that the before and after values are negative and positive.

### Using locales

The results provided by `Intl.Collator.prototype.compare()` vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:

```js
// in German, ä sorts with a
console.log(new Intl.Collator("de").compare("ä", "z"));
// -1, or some other negative value

// in Swedish, ä sorts after z
console.log(new Intl.Collator("sv").compare("ä", "z"));
// 1, or some other positive value
```

### Using options

The results provided by `Intl.Collator.prototype.compare()` can be customized using the `options` argument:

```js
// in German, ä has a as the base letter
console.log(new Intl.Collator("de", { sensitivity: "base" }).compare("ä", "a"));
// 0

// in Swedish, ä and a are separate base letters
console.log(new Intl.Collator("sv", { sensitivity: "base" }).compare("ä", "a"));
// 1, or some other positive value
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # collator-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl`


Intl.RelativeTimeFormat - JavaScript

Intl.RelativeTimeFormat
=======================

The **`Intl.RelativeTimeFormat`** object enables language-sensitive relative time formatting.

Try it
------

Constructor
-----------

`Intl.RelativeTimeFormat()`

Creates a new `Intl.RelativeTimeFormat` object.

Static methods
--------------

`Intl.RelativeTimeFormat.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.RelativeTimeFormat.prototype` and shared by all `Intl.RelativeTimeFormat` instances.

`Intl.RelativeTimeFormat.prototype.constructor`

The constructor function that created the instance object. For `Intl.RelativeTimeFormat` instances, the initial value is the `Intl.RelativeTimeFormat` constructor.

`Intl.RelativeTimeFormat.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.RelativeTimeFormat"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.RelativeTimeFormat.prototype.format()`

Formats a `value` and a `unit` according to the locale and formatting options of the given `Intl.RelativeTimeFormat` object.

`Intl.RelativeTimeFormat.prototype.formatToParts()`

Returns an `Array` of objects representing the relative time format in parts that can be used for custom locale-aware formatting.

`Intl.RelativeTimeFormat.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples
--------

### Basic format usage

The following example shows how to use a relative time formatter for the English language.

```js
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
  localeMatcher: "best fit", // other values: "lookup"
  numeric: "always", // other values: "auto"
  style: "long", // other values: "short" or "narrow"
});

// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"

// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
```

### Using formatToParts

The following example shows how to create a relative time formatter returning formatted parts.

```js
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

// Format relative time using the day unit.
rtf.formatToParts(-1, "day");
// [{ type: "literal", value: "yesterday"}]

rtf.formatToParts(100, "day");
// [
// { type: "literal", value: "in " },
// { type: "integer", value: "100", unit: "day" },
// { type: "literal", value: " days" }
// ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # relativetimeformat-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.RelativeTimeFormat` in FormatJS
* `Intl`
* `Intl.RelativeTimeFormat` on v8.dev (2018)


Intl.DisplayNames - JavaScript

Intl.DisplayNames
=================

The **`Intl.DisplayNames`** object enables the consistent translation of language, region and script display names.

Try it
------

Constructor
-----------

`Intl.DisplayNames()`

Creates a new `Intl.DisplayNames` object.

Static methods
--------------

`Intl.DisplayNames.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.DisplayNames.prototype` and shared by all `Intl.DisplayNames` instances.

`Intl.DisplayNames.prototype.constructor`

The constructor function that created the instance object. For `Intl.DisplayNames` instances, the initial value is the `Intl.DisplayNames` constructor.

`Intl.DisplayNames.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.DisplayNames"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.DisplayNames.prototype.of()`

This method receives a `code` and returns a string based on the locale and options provided when instantiating `Intl.DisplayNames`.

`Intl.DisplayNames.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.

Examples
--------

### Region Code Display Names

To create an `Intl.DisplayNames` for a locale and get the display name for a region code.

```js
// Get display names of region in English
let regionNames = new Intl.DisplayNames(["en"], { type: "region" });
regionNames.of("419"); // "Latin America"
regionNames.of("BZ"); // "Belize"
regionNames.of("US"); // "United States"
regionNames.of("BA"); // "Bosnia & Herzegovina"
regionNames.of("MM"); // "Myanmar (Burma)"

// Get display names of region in Traditional Chinese
regionNames = new Intl.DisplayNames(["zh-Hant"], { type: "region" });
regionNames.of("419"); // "拉丁美洲"
regionNames.of("BZ"); // "貝里斯"
regionNames.of("US"); // "美國"
regionNames.of("BA"); // "波士尼亞與赫塞哥維納"
regionNames.of("MM"); // "緬甸"
```

### Language Display Names

To create an `Intl.DisplayNames` for a locale and get the display name for a language-script-region sequence.

```js
// Get display names of language in English
let languageNames = new Intl.DisplayNames(["en"], { type: "language" });
languageNames.of("fr"); // "French"
languageNames.of("de"); // "German"
languageNames.of("fr-CA"); // "Canadian French"
languageNames.of("zh-Hant"); // "Traditional Chinese"
languageNames.of("en-US"); // "American English"
languageNames.of("zh-TW"); // "Chinese (Taiwan)"]

// Get display names of language in Traditional Chinese
languageNames = new Intl.DisplayNames(["zh-Hant"], { type: "language" });
languageNames.of("fr"); // "法文"
languageNames.of("zh"); // "中文"
languageNames.of("de"); // "德文"
```

### Script Code Display Names

To create an `Intl.DisplayNames` for a locale and get the display name for a script code.

```js
// Get display names of script in English
let scriptNames = new Intl.DisplayNames(["en"], { type: "script" });
// Get script names
scriptNames.of("Latn"); // "Latin"
scriptNames.of("Arab"); // "Arabic"
scriptNames.of("Kana"); // "Katakana"

// Get display names of script in Traditional Chinese
scriptNames = new Intl.DisplayNames(["zh-Hant"], { type: "script" });
scriptNames.of("Latn"); // "拉丁文"
scriptNames.of("Arab"); // "阿拉伯文"
scriptNames.of("Kana"); // "片假名"
```

### Currency Code Display Names

To create an `Intl.DisplayNames` for a locale and get the display name for currency code.

```js
// Get display names of currency code in English
let currencyNames = new Intl.DisplayNames(["en"], { type: "currency" });
// Get currency names
currencyNames.of("USD"); // "US Dollar"
currencyNames.of("EUR"); // "Euro"
currencyNames.of("TWD"); // "New Taiwan Dollar"
currencyNames.of("CNY"); // "Chinese Yuan"

// Get display names of currency code in Traditional Chinese
currencyNames = new Intl.DisplayNames(["zh-Hant"], { type: "currency" });
currencyNames.of("USD"); // "美元"
currencyNames.of("EUR"); // "歐元"
currencyNames.of("TWD"); // "新台幣"
currencyNames.of("CNY"); // "人民幣"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # intl-displaynames-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl`


Intl.Locale - JavaScript

Intl.Locale
===========

The **`Intl.Locale`** object is a standard built-in property of the Intl object that represents a Unicode locale identifier.

Try it
------

Description
-----------

The **`Intl.Locale`** object was created to allow for easier manipulation of Unicode locales. Unicode represents locales with a string, called a *locale identifier*. The locale identifier consists of a *language identifier* and *extension tags*. Language identifiers are the core of the locale, consisting of *language*, *script*, and *region subtags*. Additional information about the locale is stored in the optional *extension tags*. Extension tags hold information about locale aspects such as calendar type, clock type, and numbering system type.

Traditionally, the Intl API used strings to represent locales, just as Unicode does. This is a simple and lightweight solution that works well. Adding a Locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. The following properties of `Intl.Locale` correspond to Unicode locale identifier subtags:

| Property | Corresponding subtag |
| --- | --- |
| `language` | `language` (first part) |
| `script` | `script` (second part) |
| `region` | `region` (second/third part) |
| `calendar` | `ca` (extension) |
| `caseFirst` | `kf` (extension) |
| `collation` | `co` (extension) |
| `hourCycle` | `hc` (extension) |
| `numberingSystem` | `nu` (extension) |
| `numeric` | `kn` (extension) |

The information above is exactly provided as-is when the `Locale` object is constructed, without consulting any external database. The `Intl.Locale` object additionally provides some methods that return information about the locale's real-world information, such as available calendars, collations, and numbering systems.

Constructor
-----------

`Intl.Locale()`

Creates a new `Locale` object.

Instance properties
-------------------

These properties are defined on `Intl.Locale.prototype` and shared by all `Intl.Locale` instances.

`Intl.Locale.prototype.baseName`

Returns basic, core information about the `Locale` in the form of a substring of the complete data string.

`Intl.Locale.prototype.calendar`

Returns the part of the `Locale` that indicates the Locale's calendar era.

`Intl.Locale.prototype.caseFirst`

Returns whether case is taken into account for the locale's collation rules.

`Intl.Locale.prototype.collation`

Returns the collation type for the `Locale`, which is used to order strings according to the locale's rules.

`Intl.Locale.prototype.constructor`

The constructor function that created the instance object. For `Intl.Locale` instances, the initial value is the `Intl.Locale` constructor.

`Intl.Locale.prototype.hourCycle`

Returns the time keeping format convention used by the locale.

`Intl.Locale.prototype.language`

Returns the language associated with the locale.

`Intl.Locale.prototype.numberingSystem`

Returns the numeral system used by the locale.

`Intl.Locale.prototype.numeric`

Returns whether the locale has special collation handling for numeric characters.

`Intl.Locale.prototype.region`

Returns the region of the world (usually a country) associated with the locale.

`Intl.Locale.prototype.script`

Returns the script used for writing the particular language used in the locale.

`Intl.Locale.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.Locale"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.Locale.prototype.getCalendars()`

Returns an `Array` of available calendar identifiers, according to the locale's rules.

`Intl.Locale.prototype.getCollations()`

Returns an `Array` of the collation types for the `Locale`.

`Intl.Locale.prototype.getHourCycles()`

Returns an `Array` of hour cycle identifiers, indicating either the 12-hour clock ("h12"), the Japanese 12-hour clock ("h11"), the 24-hour clock ("h23"), or the unused format "h24".

`Intl.Locale.prototype.getNumberingSystems()`

Returns an `Array` of numbering system identifiers available according to the locale's rules.

`Intl.Locale.prototype.getTextInfo()`

Returns the part indicating the ordering of characters `ltr` (left-to-right) or `rtl` (right-to-left).

`Intl.Locale.prototype.getTimeZones()`

Returns an `Array` of time zone identifiers, associated with the `Locale`.

`Intl.Locale.prototype.getWeekInfo()`

Returns UTS 35's Week Elements according to the locale rules.

`Intl.Locale.prototype.maximize()`

Gets the most likely values for the language, script, and region of the locale based on existing values.

`Intl.Locale.prototype.minimize()`

Attempts to remove information about the locale that would be added by calling `maximize()`.

`Intl.Locale.prototype.toString()`

Returns the Locale's full locale identifier string.

Examples
--------

### Basic usage

At its very simplest, the `Intl.Locale()` constructor takes a locale identifier string as its argument:

```js
const us = new Intl.Locale("en-US");
```

### Using the Locale constructor with an options object

The constructor also takes an optional configuration object argument, which can contain any of several extension types. For example, set the `hourCycle` property of the configuration object to your desired hour cycle type, and then pass it into the constructor:

```js
const us12hour = new Intl.Locale("en-US", { hourCycle: "h12" });
console.log(us12hour.hourCycle); // Prints "h12"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # locale-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.Locale` in FormatJS
* `Intl`
* Canonical Unicode Locale Identifiers in the Unicode locale data markup language spec


Intl.supportedValuesOf() - JavaScript

Intl.supportedValuesOf()
========================

The **`Intl.supportedValuesOf()`** static method returns an array containing the supported calendar, collation, currency, numbering systems, or unit values supported by the implementation.

Duplicates are omitted and the array is sorted in ascending lexicographical order (or more precisely, using `Array.prototype.sort()` with an `undefined` compare function).

 The method can be used to feature-test whether values are supported in a particular implementation and download a polyfill only if necessary.
 It can also be used to build UIs that allow users to select their preferred localized values, for example when the UI is created from WebGL or server-side.

Try it
------

Syntax
------

```js
Intl.supportedValuesOf(key)
```

### Parameters

`key`

A key string indicating the category of values to be returned. This is one of: `"calendar"`, `"collation"`, `"currency"`, `"numberingSystem"`, `"timeZone"`, `"unit"`.

### Return value

A sorted array of unique string values indicating the values supported by the implementation for the given key.

### Exceptions

`RangeError`

Thrown if an unsupported key was passed as a parameter.

Examples
--------

### Feature testing

You can check that the method is supported by comparing to `undefined`:

```js
if (typeof Intl.supportedValuesOf !== "undefined") {
  // method is supported
}
```

### Get all values for key

 To get the supported values for calendar you call the method with the key `"calendar"`.
 You can then iterate through the returned array as shown below:

```js
Intl.supportedValuesOf("calendar").forEach((calendar) => {
  // "buddhist", "chinese", "coptic", "dangi", etc.
});
```

**Note:** The array returned for calendar values will always include the value "gregory" (gregorian).

The other values are all obtained in the same way:

```js
Intl.supportedValuesOf("collation").forEach((collation) => {
  // "compat", "dict", "emoji", etc.
});

Intl.supportedValuesOf("currency").forEach((currency) => {
  // "ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", etc.
});

Intl.supportedValuesOf("numberingSystem").forEach((numberingSystem) => {
  // "adlm", "ahom", "arab", "arabext", "bali", etc.
});

Intl.supportedValuesOf("timeZone").forEach((timeZone) => {
  // "Africa/Abidjan", "Africa/Accra", "Africa/Addis\_Ababa", "Africa/Algiers", etc.
});

Intl.supportedValuesOf("unit").forEach((unit) => {
  // "acre", "bit", "byte", "celsius", "centimeter", etc.
});
```

### Invalid key throws RangeError

```js
try {
  Intl.supportedValuesOf("someInvalidKey");
} catch (err) {
  //Error: RangeError: invalid key: "someInvalidKey"
}
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.supportedvaluesof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.supportedValuesOf` in FormatJS
* `Intl`


Intl.ListFormat - JavaScript

Intl.ListFormat
===============

The **`Intl.ListFormat`** object enables language-sensitive list formatting.

Try it
------

Constructor
-----------

`Intl.ListFormat()`

Creates a new `Intl.ListFormat` object.

Static methods
--------------

`Intl.ListFormat.supportedLocalesOf()`

Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.

Instance properties
-------------------

These properties are defined on `Intl.ListFormat.prototype` and shared by all `Intl.ListFormat` instances.

`Intl.ListFormat.prototype.constructor`

The constructor function that created the instance object. For `Intl.ListFormat` instances, the initial value is the `Intl.ListFormat` constructor.

`Intl.ListFormat.prototype[@@toStringTag]`

The initial value of the `@@toStringTag` property is the string `"Intl.ListFormat"`. This property is used in `Object.prototype.toString()`.

Instance methods
----------------

`Intl.ListFormat.prototype.format()`

Returns a language-specific formatted string representing the elements of the list.

`Intl.ListFormat.prototype.formatToParts()`

Returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.

`Intl.ListFormat.prototype.resolvedOptions()`

Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current `Intl.ListFormat` object.

Examples
--------

### Using format

The following example shows how to create a List formatter using the English language.

```js
const list = ["Motorcycle", "Bus", "Car"];

console.log(
  new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus and Car

console.log(
  new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
    list,
  ),
);
// Motorcycle, Bus or Car

console.log(
  new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list),
);
// Motorcycle Bus Car
```

### Using formatToParts

The following example shows how to create a List formatter returning formatted parts

```js
const list = ["Motorcycle", "Bus", "Car"];
console.log(
  new Intl.ListFormat("en-GB", {
    style: "long",
    type: "conjunction",
  }).formatToParts(list),
);

// [ { "type": "element", "value": "Motorcycle" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Bus" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Car" } ];
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # listformat-objects |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Polyfill of `Intl.ListFormat` in FormatJS
* `Intl`


Intl.Collator() constructor - JavaScript

Intl.Collator() constructor
===========================

The **`Intl.Collator()`** constructor creates `Intl.Collator` objects.

Try it
------

Syntax
------

```js
new Intl.Collator()
new Intl.Collator(locales)
new Intl.Collator(locales, options)

Intl.Collator()
Intl.Collator(locales)
Intl.Collator(locales, options)
```

**Note:** `Intl.Collator()` can be called with or without `new`. Both create a new `Intl.Collator` instance.

### Parameters

`locales` Optional

A string with a BCP 47 language tag or an `Intl.Locale` instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

The following Unicode extension keys are allowed:

`co`

See `collation`.

`kn`

See `numeric`.

`kf`

See `caseFirst`.

These keys can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.

`options` Optional

An object containing the following properties, in the order they are retrieved (all of them are optional):

`usage`

Whether the comparison is for sorting a list of strings or fuzzy (for the Latin script diacritic-insensitive and case-insensitive) filtering a list of strings by key. Possible values are:

`"sort"` (default)

For sorting a list of strings.

`"search"`

For filtering a list of strings by testing each list item for a full-string match against a key. With `"search"`, the caller should only pay attention to whether `compare()` returns zero or non-zero and should not distinguish the non-zero return values from each other. That is, it is inappropriate to use `"search"` for sorting/ordering.

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see Locale identification and negotiation.

`collation`

Variant collations for certain locales, such as `"emoji"`, `"pinyin"`, `"stroke"`, and so on. For a list of supported collation types, see `Intl.Locale.prototype.getCollations()`; the default is `"default"`. This option can also be set through the `co` Unicode extension key; if both are provided, this `options` property takes precedence.

`numeric`

Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are `true` and `false`; the default is `false`. This option can also be set through the `kn` Unicode extension key; if both are provided, this `options` property takes precedence.

`caseFirst`

Whether upper case or lower case should sort first. Possible values are `"upper"`, `"lower"`, and `"false"` (use the locale's default); the default is `"false"`. This option can also be set through the `kf` Unicode extension key; if both are provided, this `options` property takes precedence.

`sensitivity`

Which differences in the strings should lead to non-zero result values. Possible values are:

`"base"`

Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.

`"accent"`

Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.

`"case"`

Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.

`"variant"`

Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.

The default is `"variant"` for usage `"sort"`; it's locale dependent for usage `"search"` per spec, but the core functionality of `"search"` is accent-insensitive and case-insensitive filtering, so `"base"` makes the most sense (and perhaps `"case"`).

`ignorePunctuation`

Whether punctuation should be ignored. Possible values are `true` and `false`; the default is `false`.

### Exceptions

`RangeError`

Thrown if `locales` or `options` contain invalid values.

Examples
--------

### Using Collator

 The following example demonstrates the different potential results for a string
 occurring before, after, or at the same level as another:

```js
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
```

 Note that the results shown in the code above can vary between browsers and browser
 versions. This is because the values are implementation-specific. That is, the
 specification requires only that the before and after values are negative and
 positive.

When usage is `"search"`, the caller should only pay attention to whether the return value of `compare()` is zero or non-zero. It is inappropriate to use a `Collator` with usage `"search"` for sorting.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-the-intl-collator-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Collator`
* `Intl`


Intl.Collator.prototype.compare() - JavaScript

Intl.Collator.prototype.compare()
=================================

 The **`compare()`** method of `Intl.Collator` instances compares two
 strings according to the sort order of this collator object.

Try it
------

Syntax
------

```js
compare(string1, string2)
```

### Parameters

`string1`, `string2`

The strings to compare against each other.

### Return value

A number indicating how `string1` and `string2` compare to each other according to the sort order of this `Intl.Collator` object:

* A negative value if `string1` comes before `string2`;
* A positive value if `string1` comes after `string2`;
* 0 if they are considered equal.
Examples
--------

### Using compare for array sort

 Use the `compare` function for sorting arrays. Note that the function
 is bound to the collator from which it was obtained, so it can be passed directly to
 `Array.prototype.sort()`.

```js
const a = ["Offenbach", "Österreich", "Odenwald"];
const collator = new Intl.Collator("de-u-co-phonebk");
a.sort(collator.compare);
console.log(a.join(", ")); // "Odenwald, Österreich, Offenbach"
```

### Using compare for array search

Use the `compare` function for finding matching strings in arrays:

```js
const a = ["Congrès", "congres", "Assemblée", "poisson"];
const collator = new Intl.Collator("fr", {
  usage: "search",
  sensitivity: "base",
});
const s = "congres";
const matches = a.filter((v) => collator.compare(v, s) === 0);
console.log(matches.join(", ")); // "Congrès, congres"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.collator.prototype.compare |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Collator`
* `String.prototype.localeCompare()`


Intl.Collator.supportedLocalesOf() - JavaScript

Intl.Collator.supportedLocalesOf()
==================================

The **`Intl.Collator.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in collation without having to fall back to the runtime's default locale.

Try it
------

Syntax
------

```js
Intl.Collator.supportedLocalesOf(locales)
Intl.Collator.supportedLocalesOf(locales, options)
```

### Parameters

`locales`

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object that may have the following property:

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the Intl page.

### Return value

An array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale.

Examples
--------

### Using supportedLocalesOf()

Assuming a runtime that supports Indonesian and German but not Balinese in collation, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is not used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.Collator.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.collator.supportedlocalesof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Collator`


Intl.Collator.prototype.resolvedOptions() - JavaScript

Intl.Collator.prototype.resolvedOptions()
=========================================

 The **`resolvedOptions()`** method of `Intl.Collator` instances returns a new object with properties reflecting the locale and collation options
 computed during initialization of this collator object.

Try it
------

Syntax
------

```js
resolvedOptions()
```

### Parameters

None.

### Return value

 A new object with properties reflecting the locale and collation options computed
 during the initialization of the given `Intl.Collator` object.

Description
-----------

The resulting object has the following properties:

`locale`

 The BCP 47 language tag for the locale actually used. If any Unicode extension
 values were requested in the input BCP 47 language tag that led to this locale,
 the key-value pairs that were requested and are supported for this locale are
 included in `locale`.

`usage`, `sensitivity`, `ignorePunctuation`

 The values provided for these properties in the `options` argument or
 filled in as defaults.

`collation`

 The value requested using the Unicode extension key `"co"`, if it is
 supported for `locale`, or `"default"`.

`numeric`, `caseFirst`

 The values requested for these properties in the `options` argument or
 using the Unicode extension keys `"kn"` and `"kf"` or filled
 in as defaults. If the implementation does not support these properties, they are
 omitted.

Examples
--------

### Using the resolvedOptions method

```js
const de = new Intl.Collator("de", { sensitivity: "base" });
const usedOptions = de.resolvedOptions();

usedOptions.locale; // "de"
usedOptions.usage; // "sort"
usedOptions.sensitivity; // "base"
usedOptions.ignorePunctuation; // false
usedOptions.collation; // "default"
usedOptions.numeric; // false
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.collator.prototype.resolvedoptions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.Collator`


Intl.DateTimeFormat.prototype.format() - JavaScript

Intl.DateTimeFormat.prototype.format()
======================================

The **`format()`** method of `Intl.DateTimeFormat` instances formats a date according to the locale and formatting options of this `Intl.DateTimeFormat` object.

Try it
------

Syntax
------

```js
format(date)
```

### Parameters

`date`

The date to format.

### Return value

A string representing the given `date` formatted according to the locale and formatting options of this `Intl.DateTimeFormat` object.

Examples
--------

### Using format

 Use the `format` getter function for formatting a single date, here for
 Serbia:

```js
const options = {
  weekday: "long",
  year: "numeric",
  month: "long",
  day: "numeric",
};
const dateTimeFormat = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat.format(new Date()));
// "недеља, 7. април 2013."
```

### Using format with map

 Use the `format` getter function for formatting all dates in an array. Note
 that the function is bound to the `Intl.DateTimeFormat`
 from which it was obtained, so it can be passed directly to
 `Array.prototype.map()`.

```js
const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];
const options = { year: "numeric", month: "long" };
const dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options);
const formatted = a.map(dateTimeFormat.format);
console.log(formatted.join("; "));
// "setembro de 2012; dezembro de 2012; abril de 2012"
```

### Avoid comparing formatted date values to static values

 Most of the time, the formatting returned by `format()` is consistent.
 However, this might change in the future and isn't guaranteed for all the languages —
 output variations are by design and allowed by the specification. Most notably, the IE
 and Edge browsers insert bidirectional control characters around dates, so the output
 text will flow properly when concatenated with other text.

 For this reason you cannot expect to be able to compare the results of
 `format()` to a static value:

```js
let d = new Date("2019-01-01T00:00:00.000000Z");
let formattedDate = Intl.DateTimeFormat(undefined, {
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
}).format(d);

"1.1.2019, 01:00:00" === formattedDate;
// true in Firefox and others
// false in IE and Edge
```

**Note:** See also this StackOverflow thread
 for more details and examples.

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.datetimeformat.prototype.format |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DateTimeFormat`
* `Date.prototype.toLocaleString()`
* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toLocaleTimeString()`


Intl.DateTimeFormat() constructor - JavaScript

Intl.DateTimeFormat() constructor
=================================

The **`Intl.DateTimeFormat()`** constructor creates `Intl.DateTimeFormat` objects.

Try it
------

Syntax
------

```js
new Intl.DateTimeFormat()
new Intl.DateTimeFormat(locales)
new Intl.DateTimeFormat(locales, options)

Intl.DateTimeFormat()
Intl.DateTimeFormat(locales)
Intl.DateTimeFormat(locales, options)
```

**Note:** `Intl.DateTimeFormat()` can be called with or without `new`. Both create a new `Intl.DateTimeFormat` instance. However, there's a special behavior when it's called without `new` and the `this` value is another `Intl.DateTimeFormat` instance; see Return value.

### Parameters

`locales` Optional

A string with a BCP 47 language tag or an `Intl.Locale` instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

The following Unicode extension key is allowed:

`nu`

See `numberingSystem`.

`ca`

See `calendar`.

`hc`

See `hourCycle`.

These keys can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.

`options` Optional

An object. For ease of reading, the property list is broken into sections based on their purposes, including locale options, date-time component options, and style shortcuts.

#### Locale options

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see Locale identification and negotiation.

`calendar`

The calendar to use, such as `"chinese"`, `"gregory"`, `"persian"`, and so on. For a list of supported calendar types, see `Intl.Locale.prototype.getCalendars()`. This option can also be set through the `ca` Unicode extension key; if both are provided, this `options` property takes precedence.

`numberingSystem`

The numbering system to use for number formatting, such as `"arab"`, `"hans"`, `"mathsans"`, and so on. For a list of supported numbering system types, see `Intl.Locale.prototype.getNumberingSystems()`. This option can also be set through the `nu` Unicode extension key; if both are provided, this `options` property takes precedence.

`hour12`

Whether to use 12-hour time (as opposed to 24-hour time). Possible values are `true` and `false`; the default is locale dependent. This option overrides the `hc` locale extension tag and/or the `hourCycle` option in case both are present. It sets `hourCycle` to `"h11"` or `"h12"` when `true`, and `"h23"` or `"h24"` when `false`, the exact choice depending on the locale — for example, if the locale most prefers `"h23"` but `hour12` is `true`, then the final hour cycle is `"h11"`.

`hourCycle`

The hour cycle to use. Possible values are `"h11"`, `"h12"`, `"h23"`, and `"h24"`. This option can also be set through the `hc` Unicode extension key; if both are provided, this `options` property takes precedence.

`timeZone`

The time zone to use. The only value implementations must recognize is `"UTC"`; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as `"Asia/Shanghai"`, `"Asia/Kolkata"`, `"America/New_York"`.

#### Date-time component options

`weekday`

The representation of the weekday. Possible values are:

`"long"`

E.g., `Thursday`

`"short"`

E.g., `Thu`

`"narrow"`

E.g., `T`. Two weekdays may have the same narrow style for some locales (e.g. `Tuesday`'s narrow style is also `T`).

`era`

The representation of the era. Possible values are:

`"long"`

E.g., `Anno Domini`

`"short"`

E.g., `AD`

`"narrow"`

E.g., `A`

`year`

The representation of the year. Possible values are `"numeric"` and `"2-digit"`.

`month`

The representation of the month. Possible values are:

`"numeric"`

E.g., `3`

`"2-digit"`

E.g., `03`

`"long"`

E.g., `March`

`"short"`

E.g., `Mar`

`"narrow"`

E.g., `M`). Two months may have the same narrow style for some locales (e.g. `May`'s narrow style is also `M`).

`day`

The representation of the day. Possible values are `"numeric"` and `"2-digit"`.

`dayPeriod`

 The formatting style used for day periods like "in the morning", "am", "noon", "n" etc. Possible values are
 `"narrow"`, `"short"`, and `"long"`.

**Note:** This option only has an effect if a 12-hour clock (`hourCycle: "h12"` or `hourCycle: "h11"`) is used. Many locales use the same string irrespective of the width specified.

`hour`

The representation of the hour. Possible values are `"numeric"` and `"2-digit"`.

`minute`

The representation of the minute. Possible values are `"numeric"` and `"2-digit"`.

`second`

The representation of the second. Possible values are `"numeric"` and `"2-digit"`.

`fractionalSecondDigits`

The number of digits used to represent fractions of a second (any additional digits are truncated). Possible values are from `1` to `3`.

`timeZoneName`

The localized representation of the time zone name. Possible values are:

`"long"`

Long localized form (e.g., `Pacific Standard Time`, `Nordamerikanische Westküsten-Normalzeit`)

`"short"`

Short localized form (e.g.: `PST`, `GMT-8`)

`"shortOffset"`

Short localized GMT format (e.g., `GMT-8`)

`"longOffset"`

Long localized GMT format (e.g., `GMT-08:00`)

`"shortGeneric"`

Short generic non-location format (e.g.: `PT`, `Los Angeles Zeit`).

`"longGeneric"`

Long generic non-location format (e.g.: `Pacific Time`, `Nordamerikanische Westküstenzeit`)

**Note:** Timezone display may fall back to another format if a required string is unavailable. For example, the non-location formats should display the timezone without a specific country/city location like "Pacific Time", but may fall back to a timezone like "Los Angeles Time".

The default value for each date-time component option is `undefined`, but if all component properties are `undefined`, then `year`, `month`, and `day` default to `"numeric"`. If any of the date-time component options is specified, then `dateStyle` and `timeStyle` must be `undefined`.

`formatMatcher`

The format matching algorithm to use. Possible values are `"basic"` and `"best fit"`; the default is `"best fit"`. Implementations are required to support displaying at least the following subsets of date-time components:

* `weekday`, `year`, `month`, `day`, `hour`, `minute`, `second`
* `weekday`, `year`, `month`, `day`
* `year`, `month`, `day`
* `year`, `month`
* `month`, `day`
* `hour`, `minute`, `second`
* `hour`, `minute`

Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. The algorithm for `"best fit"` is implementation-defined, and `"basic"` is defined by the spec. This option is only used when both `dateStyle` and `timeStyle` are `undefined` (so that each date-time component's format is individually customizable).

#### Style shortcuts

`dateStyle`

The date formatting style to use when calling `format()`. Possible values are `"full"`, `"long"`, `"medium"`, and `"short"`.

`timeStyle`

The time formatting style to use when calling `format()`. Possible values are `"full"`, `"long"`, `"medium"`, and `"short"`.

**Note:** `dateStyle` and `timeStyle` can be used with each other, but not with other date-time component options (e.g. `weekday`, `hour`, `month`, etc.).

### Return value

A new `Intl.DateTimeFormat` object.

**Note:** The text below describes behavior that is marked by the specification as "optional". It may not work in all environments. Check the browser compatibility table.

Normally, `Intl.DateTimeFormat()` can be called with or without `new`, and a new `Intl.DateTimeFormat` instance is returned in both cases. However, if the `this` value is an object that is `instanceof` `Intl.DateTimeFormat` (doesn't necessarily mean it's created via `new Intl.DateTimeFormat`; just that it has `Intl.DateTimeFormat.prototype` in its prototype chain), then the value of `this` is returned instead, with the newly created `Intl.DateTimeFormat` object hidden in a `[Symbol(IntlLegacyConstructedSymbol)]` property (a unique symbol that's reused between instances).

```js
const formatter = Intl.DateTimeFormat.call(
  { \_\_proto\_\_: Intl.DateTimeFormat.prototype },
  "en-US",
  { dateStyle: "full" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: DateTimeFormat [Intl.DateTimeFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
```

Note that there's only one actual `Intl.DateTimeFormat` instance here: the one hidden in `[Symbol(IntlLegacyConstructedSymbol)]`. Calling the `format()` and `resolvedOptions()` methods on `formatter` would correctly use the options stored in that instance, but calling all other methods (e.g. `formatRange()`) would fail: "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.

This behavior, called `ChainDateTimeFormat`, does not happen when `Intl.DateTimeFormat()` is called without `new` but with `this` set to anything else that's not an `instanceof Intl.DateTimeFormat`. If you call it directly as `Intl.DateTimeFormat()`, the `this` value is `Intl`, and a new `Intl.DateTimeFormat` instance is created normally.

### Exceptions

`RangeError`

Thrown if `locales` or `options` contain invalid values.

Examples
--------

### Using DateTimeFormat

 In basic use without specifying a locale, `DateTimeFormat` uses the default
 locale and default options.

```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los\_Angeles (UTC-0800)
```

### Using timeStyle and dateStyle

```js
const shortTime = new Intl.DateTimeFormat("en", {
  timeStyle: "short",
});
console.log(shortTime.format(Date.now())); // "1:31 PM"

const shortDate = new Intl.DateTimeFormat("en", {
  dateStyle: "short",
});
console.log(shortDate.format(Date.now())); // "07/07/20"

const mediumTime = new Intl.DateTimeFormat("en", {
  timeStyle: "medium",
  dateStyle: "short",
});
console.log(mediumTime.format(Date.now())); // "07/07/20, 1:31:55 PM"
```

### Using dayPeriod

Use the `dayPeriod` option to output a string for the times of day ("in the morning", "at night", "noon", etc.). Note, that this only works when formatting for a 12 hour clock (`hourCycle: 'h12'` or `hourCycle: 'h11'`) and that for many locales the strings are the same irrespective of the value passed for the `dayPeriod`.

```js
const date = Date.UTC(2012, 11, 17, 4, 0, 42);

console.log(
  new Intl.DateTimeFormat("en-GB", {
    hour: "numeric",
    hourCycle: "h12",
    dayPeriod: "short",
    timeZone: "UTC",
  }).format(date),
);
// 4 at night" (same formatting in en-GB for all dayPeriod values)

console.log(
  new Intl.DateTimeFormat("fr", {
    hour: "numeric",
    hourCycle: "h12",
    dayPeriod: "narrow",
    timeZone: "UTC",
  }).format(date),
);
// "4 mat." (same output in French for both narrow/short dayPeriod)

console.log(
  new Intl.DateTimeFormat("fr", {
    hour: "numeric",
    hourCycle: "h12",
    dayPeriod: "long",
    timeZone: "UTC",
  }).format(date),
);
// "4 du matin"
```

### Using timeZoneName

Use the `timeZoneName` option to output a string for the timezone ("GMT", "Pacific Time", etc.).

```js
const date = Date.UTC(2021, 11, 17, 3, 0, 42);
const timezoneNames = [
  "short",
  "long",
  "shortOffset",
  "longOffset",
  "shortGeneric",
  "longGeneric",
];

for (const zoneName of timezoneNames) {
  // Do something with currentValue
  const formatter = new Intl.DateTimeFormat("en-US", {
    timeZone: "America/Los\_Angeles",
    timeZoneName: zoneName,
  });
  console.log(`${zoneName}: ${formatter.format(date)}`);
}

// Logs:
// short: 12/16/2021, PST
// long: 12/16/2021, Pacific Standard Time
// shortOffset: 12/16/2021, GMT-8
// longOffset: 12/16/2021, GMT-08:00
// shortGeneric: 12/16/2021, PT
// longGeneric: 12/16/2021, Pacific Time
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl-datetimeformat-constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DateTimeFormat`
* `Intl.supportedValuesOf()`
* `Intl`


Intl.DateTimeFormat.prototype.formatRangeToParts() - JavaScript

Intl.DateTimeFormat.prototype.formatRangeToParts()
==================================================

 The **`formatRangeToParts()`** method of `Intl.DateTimeFormat` instances returns an array of locale-specific tokens representing each part of the formatted date
 range produced by this `Intl.DateTimeFormat` object.

Try it
------

Syntax
------

```js
formatRangeToParts(startDate, endDate)
```

Examples
--------

### Basic formatRangeToParts usage

 This method receives two `Date`s and returns an `Array` of
 objects containing the *locale-specific* tokens representing each part of the formatted date range.

**Note:** The return values shown in your locale may differ from those listed below.

```js
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT
const date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT

const fmt = new Intl.DateTimeFormat("en", {
  hour: "numeric",
  minute: "numeric",
});

console.log(fmt.formatRange(date1, date2)); // '10:00 – 11:00 AM'

fmt.formatRangeToParts(date1, date2);
// [
// { type: 'hour', value: '10', source: "startRange" },
// { type: 'literal', value: ':', source: "startRange" },
// { type: 'minute', value: '00', source: "startRange" },
// { type: 'literal', value: ' – ', source: "shared" },
// { type: 'hour', value: '11', source: "endRange" },
// { type: 'literal', value: ':', source: "endRange" },
// { type: 'minute', value: '00', source: "endRange" },
// { type: 'literal', value: ' ', source: "shared" },
// { type: 'dayPeriod', value: 'AM', source: "shared" }
// ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.DateTimeFormat.prototype.formatRangeToParts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DateTimeFormat.prototype.formatRange()`
* `Intl.DateTimeFormat`


Intl.DateTimeFormat.prototype.resolvedOptions() - JavaScript

Intl.DateTimeFormat.prototype.resolvedOptions()
===============================================

The **`resolvedOptions()`** method of `Intl.DateTimeFormat` instances returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this `Intl.DateTimeFormat` object.

Try it
------

Syntax
------

```js
resolvedOptions()
```

### Parameters

None.

### Return value

 A new object with properties reflecting the locale and date and time formatting options
 computed during the initialization of the given `Intl.DateTimeFormat` object.

Description
-----------

The resulting object has the following properties:

`locale`

 The BCP 47 language tag for the locale actually used. If any Unicode extension
 values were requested in the input BCP 47 language tag that led to this locale,
 the key-value pairs that were requested and are supported for this locale are
 included in `locale`.

`calendar`

E.g. "gregory"

`numberingSystem`

 The values requested using the Unicode extension keys `"ca"` and
 `"nu"` or filled in as default values.

`timeZone`

 The value provided for this property in the `options` argument;
 defaults to the runtime's default time zone. Should never be `undefined`.

`hour12`

 The value provided for this property in the `options` argument or
 filled in as a default.

`weekday`, `era`, `year`, `month`, `day`, `hour`, `minute`, `second`, `timeZoneName`

 The values resulting from format matching between the corresponding properties in
 the `options` argument and the available combinations and
 representations for date-time formatting in the selected locale. Some of these
 properties may not be present, indicating that the corresponding components will
 not be represented in formatted output.

Examples
--------

### Using the resolvedOptions method

```js
const germanFakeRegion = new Intl.DateTimeFormat("de-XX", { timeZone: "UTC" });
const usedOptions = germanFakeRegion.resolvedOptions();

usedOptions.locale; // "de"
usedOptions.calendar; // "gregory"
usedOptions.numberingSystem; // "latn"
usedOptions.timeZone; // "UTC"
usedOptions.month; // "numeric"
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.datetimeformat.prototype.resolvedoptions |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DateTimeFormat`


Intl.DateTimeFormat.prototype.formatToParts() - JavaScript

Intl.DateTimeFormat.prototype.formatToParts()
=============================================

The **`formatToParts()`** method of `Intl.DateTimeFormat` instances allows locale-aware formatting of strings produced by this `Intl.DateTimeFormat` object.

Try it
------

Syntax
------

```js
formatToParts(date)
```

### Parameters

`date` Optional

The date to format.

### Return value

An `Array` of objects containing the formatted date in parts.

Description
-----------

 The `formatToParts()` method is useful for custom formatting of date
 strings. It returns an `Array` of objects containing the locale-specific
 tokens from which it possible to build custom strings while preserving the
 locale-specific parts. The structure the `formatToParts()` method returns,
 looks like this:

```js
[
  { type: "day", value: "17" },
  { type: "weekday", value: "Monday" },
];
```

Possible types are the following:

`day`

The string used for the day, for example `"17"`.

`dayPeriod`

 The string used for the day period, for example, `"AM"`,
 `"PM"`, `"in the morning"`, or `"noon"`

`era`

The string used for the era, for example `"BC"` or `"AD"`.

`fractionalSecond`

The string used for the fractional seconds, for example `"0"` or `"00"` or `"000"`.

`hour`

The string used for the hour, for example `"3"` or `"03"`.

`literal`

 The string used for separating date and time values, for example `"/"`,
 `","`, `"o'clock"`, `"de"`, etc.

`minute`

The string used for the minute, for example `"00"`.

`month`

The string used for the month, for example `"12"`.

`relatedYear`

 The string used for the related 4-digit Gregorian year, in the event that the
 calendar's representation would be a yearName instead of a year, for example `"2019"`.

`second`

The string used for the second, for example `"07"` or `"42"`.

`timeZone`

The string used for the name of the time zone, for example `"UTC"`. Default is the timezone of the current environment.

`weekday`

The string used for the weekday, for example `"M"`, `"Monday"`, or `"Montag"`.

`year`

The string used for the year, for example `"2012"` or `"96"`.

`yearName`

The string used for the yearName in relevant contexts, for example `"geng-zi"`

Examples
--------

`DateTimeFormat` outputs localized, opaque strings that cannot be
 manipulated directly:

```js
const date = Date.UTC(2012, 11, 17, 3, 0, 42);

const formatter = new Intl.DateTimeFormat("en-us", {
  weekday: "long",
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  fractionalSecondDigits: 3,
  hour12: true,
  timeZone: "UTC",
});

formatter.format(date);
// "Monday, 12/17/2012, 3:00:42.000 AM"
```

 However, in many User Interfaces there is a desire to customize the formatting of this
 string. The `formatToParts` method enables locale-aware formatting of strings
 produced by `DateTimeFormat` formatters by providing you the string in parts:

```js
formatter.formatToParts(date);

// return value:
[
  { type: "weekday", value: "Monday" },
  { type: "literal", value: ", " },
  { type: "month", value: "12" },
  { type: "literal", value: "/" },
  { type: "day", value: "17" },
  { type: "literal", value: "/" },
  { type: "year", value: "2012" },
  { type: "literal", value: ", " },
  { type: "hour", value: "3" },
  { type: "literal", value: ":" },
  { type: "minute", value: "00" },
  { type: "literal", value: ":" },
  { type: "second", value: "42" },
  { type: "fractionalSecond", value: "000" },
  { type: "literal", value: " " },
  { type: "dayPeriod", value: "AM" },
];
```

 Now the information is available separately and it can be formatted and concatenated
 again in a customized way. For example by using `Array.prototype.map()`,
 arrow functions,
 a switch statement,
 template literals,
 and `Array.prototype.join()`.

```js
const dateString = formatter
  .formatToParts(date)
  .map(({ type, value }) => {
    switch (type) {
      case "dayPeriod":
        return `<em>${value}</em>`;
      default:
        return value;
    }
  })
  .join("");
```

This will emphasize the day period when using the `formatToParts()` method.

```js
console.log(formatter.format(date));
// "Monday, 12/17/2012, 3:00:42.000 AM"

console.log(dateString);
// "Monday, 12/17/2012, 3:00:42.000 <em>AM</em>"
```

### Named Years and Mixed calendars

 In some cases, calendars use named years. Chinese and Tibetan calendars, for example,
 use a 60-year sexagenary cycle of named years.
 These years are disambiguated by relationship to
 corresponding years on the Gregorian calendar. When this is the case, the result of
 `formatToParts()` will contain an entry for `relatedYear` when a
 year would normally be present, containing the 4-digit Gregorian year, instead of an
 entry for `year`. Setting an entry in the bag for `year` (with any
 value) will yield both the and the `yearName` Gregorian
 `relatedYear`:

```js
const opts = { year: "numeric", month: "numeric", day: "numeric" };
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", opts);
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));

// return value
[
  { type: "relatedYear", value: "2012" },
  { type: "literal", value: "年" },
  { type: "month", value: "十一月" },
  { type: "day", value: "4" },
];
```

 If the `year` option is not set in the bag (to any value), the result will
 include only the `relatedYear`:

```js
const df = new Intl.DateTimeFormat("zh-u-ca-chinese");
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));

// return value
[
  { type: "relatedYear", value: "2012" },
  { type: "literal", value: "年" },
  { type: "month", value: "十一月" },
  { type: "day", value: "4" },
];
```

 In cases where the `year` would be output, `.format()` may
 commonly present these side-by-side:

```js
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", { year: "numeric" });
df.format(Date.UTC(2012, 11, 17, 3, 0, 42)); // 2012壬辰年
```

This also makes it possible to mix locale and calendar in both `format`:

```js
const df = new Intl.DateTimeFormat("en-u-ca-chinese", { year: "numeric" });
const date = Date.UTC(2012, 11, 17, 3, 0, 42);
df.format(date); // 2012(ren-chen)
```

And `formatToParts`:

```js
const opts = { month: "numeric", day: "numeric", year: "numeric" };
const df = new Intl.DateTimeFormat("en-u-ca-chinese", opts);
const date = Date.UTC(2012, 11, 17, 3);
df.formatToParts(date);
// [
// { type: 'month', value: '11' },
// { type: 'literal', value: '/' },
// { type: 'day', value: '4' },
// { type: 'literal', value: '/' },
// { type: 'relatedYear', value: '2012' }
// ]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-Intl.DateTimeFormat.prototype.formatToParts |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DateTimeFormat`
* `Intl.DateTimeFormat.prototype.format()`
* `Date.prototype.toLocaleString()`
* `Date.prototype.toLocaleDateString()`
* `Date.prototype.toLocaleTimeString()`


Intl.DateTimeFormat.prototype.formatRange() - JavaScript

Intl.DateTimeFormat.prototype.formatRange()
===========================================

 The **`formatRange()`** method of `Intl.DateTimeFormat` instances formats a
 date range in the most concise way based on the locales and
 options provided when instantiating this
 `Intl.DateTimeFormat` object.

Try it
------

Syntax
------

```js
formatRange(startDate, endDate)
```

### Parameters

`startDate`

A `Date` object representing the start of the date range.

`endDate`

A `Date` object representing the end of the date range.

### Return value

A string representing the given date range formatted according to the locale and formatting options of this `Intl.DateTimeFormat` object.

Examples
--------

### Basic formatRange usage

 This method receives two `Date`s and formats the date range in the most
 concise way based on the `locale` and `options` provided when
 instantiating `Intl.DateTimeFormat`.

```js
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT
const date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT
const date3 = new Date(Date.UTC(1906, 0, 20, 10, 0, 0)); // Sat, 20 Jan 1906 10:00:00 GMT

const fmt1 = new Intl.DateTimeFormat("en", {
  year: "2-digit",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
});
console.log(fmt1.format(date1)); // '1/10/06, 10:00 AM'
console.log(fmt1.formatRange(date1, date2)); // '1/10/06, 10:00 – 11:00 AM'
console.log(fmt1.formatRange(date1, date3)); // '1/10/06, 10:00 AM – 1/20/07, 10:00 AM'

const fmt2 = new Intl.DateTimeFormat("en", {
  year: "numeric",
  month: "short",
  day: "numeric",
});
console.log(fmt2.format(date1)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date2)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date3)); // 'Jan 10 – 20, 1906'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.datetimeformat.prototype.formatRange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DateTimeFormat`


Intl.DateTimeFormat.supportedLocalesOf() - JavaScript

Intl.DateTimeFormat.supportedLocalesOf()
========================================

The **`Intl.DateTimeFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.

Try it
------

Syntax
------

```js
Intl.DateTimeFormat.supportedLocalesOf(locales)
Intl.DateTimeFormat.supportedLocalesOf(locales, options)
```

### Parameters

`locales`

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object that may have the following property:

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the Intl page.

### Return value

An array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.

Examples
--------

### Using supportedLocalesOf()

Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.DateTimeFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.datetimeformat.supportedlocalesof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.DateTimeFormat`


Intl.PluralRules.prototype.selectRange() - JavaScript

Intl.PluralRules.prototype.selectRange()
========================================

The **`selectRange()`** method of `Intl.PluralRules` instances receives two values and returns a string indicating which plural rule to use for locale-aware formatting of the indicated range.

Syntax
------

```js
selectRange(startRange, endRange)
```

### Parameters

`startRange`

A number representing the start of the range.

`endRange`

A number representing the end of the range.

### Return value

 A string representing the pluralization category of the specified range.
 This can be one of `zero`, `one`, `two`, `few`, `many` or `other`, that are relevant for the locale whose localization is specified in LDML Language Plural Rules.

Description
-----------

This function selects a pluralization category according to the locale and formatting options of an `Intl.PluralRules` object.

 Conceptually the behavior is the same as getting plural rules for a single cardinal or ordinal number.
 Languages have one or more forms for describing ranges, and this method returns the appropriate form given the supplied locale and formatting options.
 In English there is only one plural form, such as "1–10 apples", and the method will return `other`.
 Other languages can have many forms.

Examples
--------

### Using selectRange()

```js
new Intl.PluralRules("sl").selectRange(102, 201); // 'few'

new Intl.PluralRules("pt").selectRange(102, 102); // 'other'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.pluralrules.prototype.selectrange |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.PluralRules`


Intl.PluralRules.prototype.select() - JavaScript

Intl.PluralRules.prototype.select()
===================================

The **`select()`** method of `Intl.PluralRules` instances returns a string indicating which plural rule to use for locale-aware formatting of a number.

Try it
------

Syntax
------

```js
select(number)
```

### Parameters

`number`

The number to get a plural rule for.

### Return value

 A string representing the pluralization category of the `number`.
 This can be one of `zero`, `one`, `two`, `few`, `many`, or `other`.

Description
-----------

 This function selects a pluralization category according to the locale and formatting options of an `Intl.PluralRules` object.
 These options are set in the `Intl.PluralRules()` constructor.

Examples
--------

### Using select()

 First, create an `Intl.PluralRules` object, passing the appropriate `locales` and `options` parameters.
 Here we create a plural rules object for Arabic in the Egyptian dialect.
 Because the `type` is not specified the rules object will provide formatting for cardinal numbers (the default).

```js
const pr = new Intl.PluralRules("ar-EG");
```

 Then call `select()` on the rules object, specifying the number for which the plural form is required.
 Note that Arabic has 5 forms for cardinal numbers, as shown.

```js
pr.select(0); // 'zero'
pr.select(1); // 'one'
pr.select(2); // 'two'
pr.select(6); // 'few'
pr.select(18); // 'many'
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.pluralrules.prototype.select |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.PluralRules`


Intl.PluralRules.supportedLocalesOf() - JavaScript

Intl.PluralRules.supportedLocalesOf()
=====================================

The **`Intl.PluralRules.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in plural rules without having to fall back to the runtime's default locale.

Try it
------

Syntax
------

```js
Intl.PluralRules.supportedLocalesOf(locales)
Intl.PluralRules.supportedLocalesOf(locales, options)
```

### Parameters

`locales`

A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see the parameter description on the `Intl` main page.

`options` Optional

An object that may have the following property:

`localeMatcher`

The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the Intl page.

### Return value

An array of strings representing a subset of the given locale tags that are supported in plural rules without having to fall back to the runtime's default locale.

Examples
--------

### Using supportedLocalesOf()

Assuming a runtime that supports Indonesian and German but not Balinese in plural rules, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to plural rules nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.

```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.PluralRules.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```

Specifications
--------------

| Specification |
| --- |
| ECMAScript Internationalization API Specification # sec-intl.pluralrules.supportedlocalesof |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `Intl.PluralRules`