Formatting data
A major use case of Intl is to output locale-specific texts representing structured data. This is similar to translation software, but instead of letting you translate arbitrary text, it takes data such as dates, numbers, and lists, and formats them according to locale-specific rules.
The Intl.DateTimeFormat, Intl.DurationFormat, Intl.ListFormat, Intl.NumberFormat, and Intl.RelativeTimeFormat objects each format one kind of data. Each instance provides two methods:
format(): Takes a piece of data and returns a string using the formatting rule as determined by the locale and options.formatToParts(): Takes the same data and returns the same string, but broken down into parts, each part being an object with atypeand avalue. This is useful for more advanced use cases, such as interleaving the formatted text with other texts.
For example, here's a typical use of the Intl.NumberFormat object:
// 1. Construct a formatter object, specifying the locale and formatting options:
const price = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
});
// 2. Use the `format` method of the formatter object to format a number:
console.log(price.format(5.259)); // $5.26
// Or, use the `formatToParts` method to get the formatted number
// broken down into parts:
console.table(price.formatToParts(5.259));
// | | type | value |
// | 0 | "currency" | "$" |
// | 1 | "integer" | "5" |
// | 2 | "decimal" | "." |
// | 3 | "fraction" | "26" |
You don't always have to construct a formatter object in order to format strings. For casual use, you can also directly call the toLocaleString() method on the data, passing the locale and options as arguments. The toLocaleString() method is implemented by Temporal.PlainDate.prototype.toLocaleString(), Temporal.Duration.prototype.toLocaleString(), Number.prototype.toLocaleString(), and so on. Read the documentation for the data you are formatting to see if it supports toLocaleString(), and what formatter options it corresponds to.
console.log(
(5.259).toLocaleString("en-US", {
style: "currency",
currency: "USD",
}),
); // $5.26
Note that toLocaleString() is potentially less efficient than using a formatter object, because every time toLocaleString is called, it has to perform a search in a big database of localization strings. When the method is called many times with the same arguments, it is better to create a formatter object and use its format() method, because a formatter object remembers the arguments passed to it and may decide to cache a slice of the database, so future format calls can search for localization strings within a more constrained context.
Date and time formatting
Intl.DateTimeFormat formats dates and times, as well as ranges of dates and times. The DateTimeFormat object takes date/time inputs in one of the following forms: Date, Temporal.PlainDateTime, Temporal.PlainTime, Temporal.PlainDate, Temporal.PlainYearMonth, or Temporal.PlainMonthDay.
Note:
You can't pass a Temporal.ZonedDateTime object directly, because the time zone is already fixed in the object. You should use Temporal.ZonedDateTime.prototype.toLocaleString() or convert it to a Temporal.PlainDateTime object first.
Common use cases of localized date and time formatting are as follows:
- Output the same date and time in another calendar system, such as the Islamic, Hebrew, or Chinese calendar.
- Output the same real-world time (instant) but in another time zone.
- Selectively output certain components of the date and time, such as only the year and month, and the specific representation of them (such as "Thursday" or "Thu").
- Output the date according to locale-specific conventions, such as MM/DD/YYYY as in the U.S., DD/MM/YYYY as in the U.K., or YYYY/MM/DD as in Japan.
- Output the time according to locale-specific conventions, such as 12-hour or 24-hour clock.
To decide what the formatted string looks like, you first choose the calendar (which affects the year, month, week, and day calculation) and time zone (which affects the exact time as well as possibly the date). This is done using the aforementioned calendar option (or the -ca- extension key in the locale identifier), and the timeZone option.
Dateobjects represent a unique instant in the user's time zone and in the ISO 8601 calendar (as reported by methods likeDate.prototype.getHours()andDate.prototype.getMonth()). They are converted to the givencalendarandtimeZoneby preserving the instant, so the date and time components may change.- The various
Temporalobjects already have a calendar built-in, so thecalendaroption must be consistent with the calendar of the object—unless the date's calendar is"iso8601", in which case it is converted to the requestedcalendar. These objects don't have a time zone, so they are directly displayed in the giventimeZonewithout conversion.
Here we demonstrate how the combination of calendar and timeZone configurations result in different representations of the same instant.
// Assume that the local time zone is UTC
const targetDate = new Date(2022, 0, 1); // 2022-01-01 midnight in the local time zone
const results = [];
for (const calendar of ["gregory", "hebrew"]) {
for (const timeZone of ["America/New_York", "Asia/Tokyo"]) {
const df = new Intl.DateTimeFormat("en-US", {
calendar,
timeZone,
// More on these later
dateStyle: "full",
timeStyle: "full",
});
results.push({ calendar, timeZone, output: df.format(targetDate) });
}
}
console.table(results);
The output looks like this:
| calendar | timeZone | output |
|---|---|---|
| 'gregory' | 'America/New_York' | 'Friday, December 31, 2021 at 7:00:00 PM Eastern Standard Time' |
| 'gregory' | 'Asia/Tokyo' | 'Saturday, January 1, 2022 at 9:00:00 AM Japan Standard Time' |
| 'hebrew' | 'America/New_York' | 'Friday, 27 Tevet 5782 at 7:00:00 PM Eastern Standard Time' |
| 'hebrew' | 'Asia/Tokyo' | 'Saturday, 28 Tevet 5782 at 9:00:00 AM Japan Standard Time' |
A date/time is comprised of the following components: weekday, era, year, month, day, dayPeriod, hour, minute, second, fractionalSecondDigits, and timeZoneName. Your next decision is what components to include in the output, and what forms they should take. You have two choices:
- You can manually configure each component, using options with the same name as the component. Only the components you specify will be included in the output, with the specified form.
- You can use the shortcuts
dateStyleandtimeStyle, which are predefined sets of components. They expand to a set of component options depending on the locale.
You should pick one of these two methods, because they are mutually exclusive. Using both methods simultaneously will result in an error.
Underlyingly, after requesting a combination of components, the DateTimeFormat object looks for a "template" that matches the requested components, so it only needs to fill in the values one by one. Not every combination of components has a predefined template. DateTimeFormat has a formatMatcher option that decides how to negotiate, by making components longer or shorter than requested, or by omitting or adding components. It gets quite technical, so you should read the Intl.DateTimeFormat() reference to better understand how it handles this.
Here, we demonstrate a few common ways to format the components:
const df1 = new Intl.DateTimeFormat("en-US", {
// Include all components (usually)
dateStyle: "full",
timeStyle: "full",
});
const df2 = new Intl.DateTimeFormat("en-US", {
// Display the calendar date
era: "short",
year: "numeric",
month: "long",
day: "numeric",
});
const df3 = new Intl.DateTimeFormat("en-US", {
// Display a time like on a digital clock
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
timeZoneName: "shortOffset",
});
const targetDate = new Date(2022, 0, 1, 12, 34, 56); // 2022-01-01 12:34:56 in the local time zone
console.log(df1.format(targetDate));
// Saturday, January 1, 2022 at 12:34:56 PM Coordinated Universal Time
// January 1, 2022 AD
// 12:34:56 PM GMT
There are other customization options. For example, you can use the hourCycle option to display the time in 12-hour or 24-hour and show midnight/noon as 12:00 or 0:00. You can also use the numberingSystem option to display any numbers in another numbering system.
Apart from format(), there's a second important method, formatRange(), which formats a range of dates or times. It takes two date-times of the same type, formats each one, joins them with a range separator (like the en-dash), and deduplicates the common parts.
const springBreak = {
start: new Date(2023, 2, 10),
end: new Date(2023, 2, 26),
};
const df = new Intl.DateTimeFormat("en-US", { dateStyle: "long" });
console.log(df.formatRange(springBreak.start, springBreak.end));
// March 10 – 26, 2023Number formatting
Number formatting is done with the Intl.NumberFormat object. The NumberFormat object accepts inputs in the form of numbers, strings, or BigInt values. Passing a string or BigInt instead of a number allows you to format numbers that are too large or too small to be represented precisely as a JavaScript number.
Common use cases of localized number formatting are as follows:
- Output the number in another numbering system (script), such as Chinese, Arabic, or Roman.
- Output the number with locale-specific conventions, such as the decimal symbol ("." in English, but "," in many European cultures), or digit grouping (3 digits in English, but may be 4 or 2 in other cultures, and may use ",", " ", or ".").
- Output the number with exponential notation such as "3.7 million" or "2 thousand".
- Output the number as a currency, applying specific currency symbols and rounding rules. For example, monetary values less than one cent in the U.S. or less than one yen in Japan may not be meaningful to display.
- Output the number as a percentage, applying locale-specific conversion and formatting rules.
- Output the number with units, such as "meters" or "liters", with translated unit names.
To decide what the formatted string looks like, you first choose the numbering system (which affects the characters used for the digits). The purpose of a numbering system is already discussed in locale information. Another option you need to decide is the style, which sets the context for what the number represents, and potentially affects other options' default values. It is one of "decimal", "percent", "currency", or "unit". If you want to format currencies, then you also need to provide the currency option. If you want to format units, then you also need to provide the unit option.
const results = [];
for (const options of [
{ style: "decimal" }, // Format the number as a dimensionless decimal
{ style: "percent" }, // Format the number as a percentage; it is multiplied by 100
{ style: "currency", currency: "USD" }, // Format the number as a US dollar amount
{ style: "unit", unit: "meter" }, // Format the number as a length in meters
]) {
const nf = new Intl.NumberFormat("en-US", options);
results.push({ style: options.style, output: nf.format(1234567.89) });
}
console.table(results);
The output looks like:
| style | output |
|---|---|
| 'decimal' | '1,234,567.89' |
| 'percent' | '123,456,789%' |
| 'currency' | '$1,234,567.89' |
| 'unit' | '1,234,567.89 m' |
The next group of options all specify what the numeric part should look like. First, you may want to represent extremely large values in a more readable way. You can set the notation option to "scientific" or "engineering", which both use the 1.23e+6 notation. The difference is that the latter uses multiples of 3 for the exponent, keeping the mantissa (the part before the e symbol) between 1 and 1000, while the former can use any integer for the exponent, keeping the mantissa between 1 and 10. You can also set notation to "compact" to use a more human-readable notation.
const results = [];
for (const options of [
{ notation: "scientific" },
{ notation: "engineering" },
{ notation: "compact", compactDisplay: "short" }, // "short" is default
{ notation: "compact", compactDisplay: "long" },
]) {
const nf = new Intl.NumberFormat("en-US", options);
results.push({
notation: options.compactDisplay
? `${options.notation}-${options.compactDisplay}`
: options.notation,
output: nf.format(12000),
});
}
console.table(results);
The output looks like:
| notation | output |
|---|---|
| 'scientific' | '1.2E4' |
| 'engineering' | '12E3' |
| 'compact-short' | '12K' |
| 'compact-long' | '12 thousand' |
Then, you may want to round the number (if you specified notation, then just the mantissa part), so you don't display a number that's too long. These are the digit options, which include:
minimumIntegerDigitsminimumFractionDigitsmaximumFractionDigitsminimumSignificantDigitsmaximumSignificantDigitsroundingPriorityroundingIncrementroundingMode
The exact interaction of these options is quite complex and not worth covering here. You should read the digit options reference for more detail. Nevertheless, the general idea is straightforward: we first find the number of decimal places we want to keep, then we round excess decimal places off, either rounding down or up, depending on the value of the last digit.
const results = [];
for (const options of [
{ minimumFractionDigits: 4, maximumFractionDigits: 4 },
{ minimumSignificantDigits: 4, maximumSignificantDigits: 4 },
{ minimumFractionDigits: 0, maximumFractionDigits: 0, roundingMode: "floor" },
{
minimumFractionDigits: 0,
maximumFractionDigits: 0,
roundingMode: "floor",
roundingIncrement: 10,
},
]) {
const nf = new Intl.NumberFormat("en-US", options);
results.push({
options,
output: nf.format(1234.56789),
});
}
console.table(results);
The output looks like this:
| options | output |
|---|---|
{ minimumFractionDigits: 4, maximumFractionDigits: 4 } |
'1,234.5679' |
{ minimumSignificantDigits: 4, maximumSignificantDigits: 4 } |
'1,235' |
{ minimumFractionDigits: 0, maximumFractionDigits: 0, roundingMode: "floor" } |
'1,234' |
{ minimumFractionDigits: 0, maximumFractionDigits: 0, roundingMode: "floor", roundingIncrement: 10 } |
'1,230' |
There are other customization options. For example, you can use the useGrouping and signDisplay options to customize whether and how to show the group separators (like "," in "1,234,567.89") and the sign. However, note that the characters used for the group separator, decimal point, and sign are locale-specific, so you can't customize them directly.
Apart from format(), there's a second important method, formatRange(), which formats a range of numbers. It takes two number representations, formats each one, joins them with a range separator (like the en-dash), and potentially deduplicates the common parts.
const heightRange = {
min: 1.63,
max: 1.95,
};
const nf = new Intl.NumberFormat("en-US", { style: "unit", unit: "meter" });
console.log(nf.formatRange(heightRange.min, heightRange.max));
// 1.63–1.95 mList formatting
You may already have written code that does this:
const fruits = ["apple", "banana", "cherry"];
console.log(`I like ${fruits.join(", ")}.`);
// I like apple, banana, cherry.
This code is not internationalized. In some languages, the list separator is not a comma. In most languages (including English), you need a conjunction before the last item. But even just adding an "and" manually doesn't make it correct among all English speakers, because there's the debate of Oxford commas in English: "apple, banana, and cherry" vs. "apple, banana and cherry".
The Intl.ListFormat object solves this problem. It takes an array of strings and joins them in a locale-specific way such that the result represents a conjunction (and), disjunction (or), or a list of units.
const fruits = ["apple", "banana", "cherry"];
const lf = new Intl.ListFormat("en-US", { style: "long", type: "conjunction" });
console.log(`I like ${lf.format(fruits)}.`);
// I like apple, banana, and cherry.
const lf = new Intl.ListFormat("en-US", { style: "long", type: "disjunction" });
console.log(`I can give you ${lf.format(fruits)}.`);
// I can give you apple, banana, or cherry.
Check Intl.ListFormat() for more examples and options.
Relative time formatting
Intl.RelativeTimeFormat formats a time difference. The RelativeTimeFormat object takes relative times in the form of two arguments: a number (with any sign) and a time unit, such as "day", "hour", or "minute".
It does several things at once:
- It localizes and pluralizes the time unit, such as "1 day" vs. "2 days", like in number formatting.
- It chooses the appropriate phrase for past and future times, such as "in 1 day" vs. "1 day ago".
- It may select a special phrase for some time units, such as "1 day ago" vs. "yesterday".
const rtf = new Intl.RelativeTimeFormat("en-US", { numeric: "auto" });
console.log(rtf.format(1, "day")); // tomorrow
console.log(rtf.format(2, "day")); // in 2 days
console.log(rtf.format(-1, "hour")); // 1 hour ago
Check Intl.RelativeTimeFormat() for more examples and options.
Duration formatting
Intl.DurationFormat provides duration formatting, such as "3 hours, 4 minutes, 5 seconds". It is not a primitive operation with its own formatter: it uses Intl.NumberFormat and Intl.ListFormat internally to format each duration component, then joins them with a list separator. The DurationFormat object takes durations in the form of a Temporal.Duration object, or a plain object with the same properties.
Apart from customizing the numbering system, the duration formatting options decides whether or not to show each component, and how long they should be.
console.log(
new Intl.DurationFormat("en-US", {
style: "long",
}).format({ hours: 3, minutes: 4, seconds: 5 }),
);
// 3 hours, 4 minutes, and 5 seconds
Check Intl.DurationFormat() for more examples and options.