Intl.RelativeTimeFormat
Intl.RelativeTimeFormat 物件啟用語言敏感的相對時間格式化。
試一試
const rtf1 = new Intl.RelativeTimeFormat("en", { style: "short" });
console.log(rtf1.format(3, "quarter"));
// Expected output: "in 3 qtrs."
console.log(rtf1.format(-1, "day"));
// Expected output: "1 day ago"
const rtf2 = new Intl.RelativeTimeFormat("es", { numeric: "auto" });
console.log(rtf2.format(2, "day"));
// Expected output: "pasado mañana"
建構函式
Intl.RelativeTimeFormat()-
建立一個新的
Intl.RelativeTimeFormat物件。
靜態方法
Intl.RelativeTimeFormat.supportedLocalesOf()-
返回一個數組,其中包含提供的區域設定中受支援的那些區域設定,而無需回退到執行時預設區域設定。
例項屬性
這些屬性定義在 Intl.RelativeTimeFormat.prototype 上,並被所有 Intl.RelativeTimeFormat 例項共享。
Intl.RelativeTimeFormat.prototype.constructor-
建立例項物件的建構函式。對於
Intl.RelativeTimeFormat例項,初始值為Intl.RelativeTimeFormat建構函式。 Intl.RelativeTimeFormat.prototype[Symbol.toStringTag]-
[Symbol.toStringTag]屬性的初始值為字串"Intl.RelativeTimeFormat"。此屬性用於Object.prototype.toString()。
例項方法
Intl.RelativeTimeFormat.prototype.format()-
根據給定
Intl.RelativeTimeFormat物件的區域設定和格式化選項,格式化value和unit。 Intl.RelativeTimeFormat.prototype.formatToParts()-
返回一個物件陣列,這些物件表示相對時間格式的各個部分,可用於自定義的、符合區域設定的格式化。
Intl.RelativeTimeFormat.prototype.resolvedOptions()-
返回一個新物件,其屬性反映在物件初始化過程中計算出的語言環境和格式化選項。
示例
基本格式用法
以下示例展示瞭如何為英語語言使用相對時間格式化器。
js
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
使用 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 規範 # relativetimeformat-objects |
瀏覽器相容性
載入中…
另見
- FormatJS 中
Intl.RelativeTimeFormat的 Polyfill Intl- v8.dev 上的
Intl.RelativeTimeFormat(2018)