Intl.RelativeTimeFormat 对象用于语言敏感的相对时间的格式化。
JavaScript Demo: 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/RelativeTimeFormat
- : 创建一个新的
Intl.RelativeTimeFormat对象。
- : 创建一个新的
静态方法
- Intl/RelativeTimeFormat/supportedLocalesOf
- : 返回一个数组,其中包含提供的区域(locale)中被运行时所支持的,而不必回退到运行时的默认区域。
实例方法
- Intl/RelativeTimeFormat/format
- : 根据给定的
Intl.RelativeTimeFormat对象的区域和格式化选项来格式化值(value)和单位(unit)。
- : 根据给定的
- Intl/RelativeTimeFormat/formatToParts
- : 返回一个对象Array,其中的对象表示的是相对事件格式字符串中的各个部分,可用于自定义本地化格式。
- Intl/RelativeTimeFormat/resolvedOptions
- : 返回一个新的对象,其属性反映了在对象初始化期间计算所得的区域和一系列选项。
示例
基本 format 用法
以下示例显示如何为英语创建相对时间格式化程序。
// 在你的区域下创建相对时间格式化程序
// 显式传入默认值。
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "bestfit", // 其他值:"lookup"
numeric: "always", // 其他值:"auto"
style: "long", // 其他值:"short"或"narrow"
});
// 使用负值(-1)格式化相对时间。
rtf.format(-1, "day"); // "1 day ago"
// 使用正值(1)格式化相对时间。
rtf.format(1, "day"); // "in 1 day"
使用 formatToParts
以下示例展示了如何创建一个用于返回格式化后的每一个部分的相对时间格式化程序。
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// 使用日期单位格式化相对时间。
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" }
// ]
规范
浏览器兼容性
参见
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
