Intl.DurationFormat.prototype.format()
Intl.DurationFormat 例項的 format() 方法根據此 Intl.DurationFormat 物件的區域設定和格式化選項來格式化時長。
語法
js
format(duration)
引數
duration-
要格式化的時長物件。它應該包含以下一個或多個屬性:
years、months、weeks、days、hours、minutes、seconds、milliseconds、microseconds、nanoseconds。每個屬性的值都應為整數,並且它們的符號應保持一致。這可以是一個Temporal.Duration物件;有關這些屬性的更多資訊,請參閱Temporal.Duration文件。
返回值
一個表示給定 duration 的字串,該字串根據此 Intl.DurationFormat 物件的區域設定和格式化選項進行格式化。
注意: 大多數情況下,format() 返回的格式是一致的。然而,輸出可能因實現而異,即使在同一區域設定下也是如此 — 輸出差異是故意的,並且規範允許。它也可能不是您期望的。例如,字串可能使用不間斷空格,或者被雙向控制字元包圍。您不應將 format() 的結果與硬編碼的常量進行比較。
示例
使用 format()
以下示例展示瞭如何使用英語建立 Duration 格式化器。
js
const duration = {
years: 1,
months: 2,
weeks: 3,
days: 3,
hours: 4,
minutes: 5,
seconds: 6,
milliseconds: 7,
microseconds: 8,
nanoseconds: 9,
};
// Without options, style defaults to "short"
new Intl.DurationFormat("en").format(duration);
// "1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns"
// With style set to "long"
new Intl.DurationFormat("en", { style: "long" }).format(duration);
// "1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds, 8 microseconds, 9 nanoseconds"
// With style set to "narrow"
new Intl.DurationFormat("en", { style: "narrow" }).format(duration);
// "1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns"
使用不同區域設定和樣式的 format()
js
const duration = {
hours: 1,
minutes: 46,
seconds: 40,
};
// With style set to "long" and locale "fr-FR"
new Intl.DurationFormat("fr-FR", { style: "long" }).format(duration);
// "1 heure, 46 minutes et 40 secondes"
// With style set to "short" and locale set to "en"
new Intl.DurationFormat("en", { style: "short" }).format(duration);
// "1 hr, 46 min and 40 sec"
// With style set to "short" and locale set to "pt"
new Intl.DurationFormat("pt", { style: "narrow" }).format(duration);
// "1 h 46 min 40 s"
// With style set to "digital" and locale set to "en"
new Intl.DurationFormat("en", { style: "digital" }).format(duration);
// "1:46:40"
// With style set to "digital", locale set to "en", and hours set to "long"
new Intl.DurationFormat("en", { style: "digital", hours: "long" }).format(
duration,
);
// "1 hour, 46:40"
使用 fractionalDigits 選項的 format()
js
const duration = {
hours: 11,
minutes: 30,
seconds: 12,
milliseconds: 345,
microseconds: 600,
};
new Intl.DurationFormat("en", { style: "digital" }).format(duration);
// "11:30:12.3456"
new Intl.DurationFormat("en", { style: "digital", fractionalDigits: 5 }).format(
duration,
);
// "11:30:12.34560"
new Intl.DurationFormat("en", { style: "digital", fractionalDigits: 3 }).format(
duration,
);
// "11:30:12.346"
規範
| 規範 |
|---|
| Intl.DurationFormat # sec-Intl.DurationFormat.prototype.format |
瀏覽器相容性
載入中…