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

瀏覽器相容性

另見