Intl.RelativeTimeFormat.prototype.formatToParts()

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上使用。自 2020 年 9 月起,所有浏览器均已提供此功能。

formatToParts() 方法属于 Intl.RelativeTimeFormat 实例,它返回一个对象数组,表示由 format() 方法格式化后的字符串中的每个部分。这对于基于特定区域设置的 token 构建自定义字符串非常有用。

试一试

const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
const parts = rtf.formatToParts(10, "seconds");

console.log(parts[0].value);
// Expected output: "in "

console.log(parts[1].value);
// Expected output: "10"

console.log(parts[2].value);
// Expected output: " seconds"

语法

js
formatToParts(value, unit)

参数

value

用于国际化相对时间消息的数值。

unit

用于国际化相对时间消息的单位。可能的值包括:"year""quarter""month""week""day""hour""minute""second"。也允许使用复数形式。

返回值

一个包含格式化相对时间(以部分形式)的对象 Array。每个对象包含两个或三个属性:typevalue,以及可选的 unit,每个属性都包含一个字符串。按给定顺序连接 value 字符串将得到与 format() 相同的字符串。这些部分可以看作是直接通过调用 Intl.NumberFormat.prototype.formatToParts() 并只传递 numberingSystem 选项获得的,然后添加额外的 type: "literal" token,例如 "in "" days ago" 等。由 NumberFormat 生成的所有 token 都附加了 unit 属性,它是输入 unit 的单数形式;这用于编程目的,并且不会被本地化。本地化的单位作为字面 token 的一部分输出。

options.numeric"auto" 且该值有一个特殊字符串时,返回的数组是一个单独的字面 token。

示例

使用 formatToParts()

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" }
// ]

规范

规范
ECMAScript® 2026 国际化 API 规范
# sec-Intl.RelativeTimeFormat.prototype.formatToParts

浏览器兼容性

另见