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)