Intl.RelativeTimeFormat.prototype.formatToParts()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

The formatToParts() method of Intl.RelativeTimeFormat instances returns an array of objects representing each part of the formatted string that would be returned by format(). It is useful for building custom strings from the locale-specific tokens.

Try it

Syntax

formatToParts(value, unit)

Parameters

value

Numeric value to use in the internationalized relative time message.

unit

Unit to use in the relative time internationalized message. Possible values are: "year", "quarter", "month", "week", "day", "hour", "minute", "second". Plural forms are also permitted.

Return value

An Array of objects containing the formatted relative time in parts. Each object has two or three properties, type, value, and optionally unit, each containing a string. The string concatenation of value, in the order provided, will result in the same string as format(). The parts can be thought of as directly obtained from calling Intl.NumberFormat.prototype.formatToParts() with the numeric value, passing only the numberingSystem option, and then adding additional type: "literal" tokens, such as "in ", " days ago", etc. All tokens that are produced by the NumberFormat have an additional unit property, which is the singular form of the input unit; this is for programmatic usage and is not localized. The localized unit is output as a part of a literal token.

When options.numeric is "auto", and there's a special string for the value, the returned array is a single literal token.

Examples

Using formatToParts()

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

Browser compatibility

Desktop Mobile Server
Chrome Edge Firefox Opera Safari Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet WebView Android Deno Node.js
formatToParts 71 79 70 58 14 71 79 50 14 10.0 71 1.8
12.0.0Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() constructor for more details.

See also

© 2005–2024 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts