Intl.DurationFormat.prototype.formatToParts()

基準線 2025
新推出

自 ⁨2025 年 3 月⁩ 起,此功能可在最新的裝置和瀏覽器版本上使用。此功能可能在舊裝置或瀏覽器上無法正常工作。

formatToParts() 方法 Intl.DurationFormat 例項會返回一個物件陣列,這些物件代表 format() 方法會返回的格式化字串的每個部分。它對於使用區域設定特定的標記構建自定義字串很有用。

語法

js
formatToParts(duration)

引數

duration 可選

要格式化的持續時間物件。它應該包含以下一個或多個屬性:years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds。每個屬性的值都應該是一個整數,並且它們的符號應該是一致的。這可以是一個 Temporal.Duration 物件;有關這些屬性的更多資訊,請參閱 Temporal.Duration 文件。

返回值

一個包含部分格式化持續時間的 Array 物件。每個物件有兩個或三個屬性:typevalue,以及可選的 unit,它們都包含一個字串。按順序連線 value 字串將得到與 format() 相同的字串。這些部分可以被視為直接透過呼叫 Intl.NumberFormat.prototype.formatToParts() 並傳入數值及其各自的單位而獲得的。NumberFormat 生成的所有標記都有一個額外的 unit 屬性,該屬性是輸入 unit 的單數形式;這用於程式設計用途,並且不會進行本地化。本地化的單位作為 NumberFormat 結果的一部分,作為單獨的 unit 標記輸出。每個持續時間單位的部分將按照呼叫 Intl.ListFormat.prototype.formatToParts() 並使用 { type: "unit" } 的方式連線起來,因此會插入額外的文字標記。

示例

formatToParts 方法透過將字串分解為各個部分,從而支援 DurationFormat 格式化程式生成的字串的區域設定感知格式化。

js
const duration = {
  hours: 7,
  minutes: 8,
  seconds: 9,
  milliseconds: 123,
  microseconds: 456,
  nanoseconds: 789,
};

new Intl.DurationFormat("en", { style: "long" }).formatToParts(duration);

// Returned value:
[
  { type: "integer", value: "7", unit: "hour" },
  { type: "literal", value: " ", unit: "hour" },
  { type: "unit", value: "hours", unit: "hour" },
  { type: "literal", value: ", " },
  { type: "integer", value: "8", unit: "minute" },
  { type: "literal", value: " ", unit: "minute" },
  { type: "unit", value: "minutes", unit: "minute" },
  { type: "literal", value: ", " },
  { type: "integer", value: "9", unit: "second" },
  { type: "literal", value: " ", unit: "second" },
  { type: "unit", value: "seconds", unit: "second" },
  { type: "literal", value: ", " },
  { type: "integer", value: "123", unit: "millisecond" },
  { type: "literal", value: " ", unit: "millisecond" },
  { type: "unit", value: "milliseconds", unit: "millisecond" },
  { type: "literal", value: ", " },
  { type: "integer", value: "456", unit: "microsecond" },
  { type: "literal", value: " ", unit: "microsecond" },
  { type: "unit", value: "microseconds", unit: "microsecond" },
  { type: "literal", value: ", " },
  { type: "integer", value: "789", unit: "nanosecond" },
  { type: "literal", value: " ", unit: "nanosecond" },
  { type: "unit", value: "nanoseconds", unit: "nanosecond" },
];

規範

規範
Intl.DurationFormat
# sec-Intl.DurationFormat.prototype.formatToParts

瀏覽器相容性

另見