Intl.RelativeTimeFormat.prototype.format()

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上使用。自 2020 年 9 月起,所有浏览器均已提供此功能。

format() 方法是 Intl.RelativeTimeFormat 实例的方法,它根据此 Intl.RelativeTimeFormat 对象的地区和格式化选项来格式化 valueunit

试一试

const rtf = new Intl.RelativeTimeFormat("en", { style: "short" });

console.log(rtf.format(3, "quarter"));
// Expected output: "in 3 qtrs."

console.log(rtf.format(-1, "day"));
// Expected output: "1 day ago"

console.log(rtf.format(10, "seconds"));
// Expected output: "in 10 sec."

语法

js
format(value, unit)

参数

value

用于国际化相对时间消息的数值。

unit

用于相对时间国际化消息的单位。可能的值为:"year""quarter""month""week""day""hour""minute""second"。也允许使用复数形式。

返回值

一个字符串,表示给定 valueunit 根据此 Intl.RelativeTimeFormat 对象的地区和格式化选项格式化后的结果。

注意: 大多数情况下,format() 返回的格式是一致的。然而,输出可能因实现而异,即使在同一区域设置下也是如此 — 输出差异是故意的,并且规范允许。它也可能不是您期望的。例如,字符串可能使用不间断空格,或者被双向控制字符包围。您不应将 format() 的结果与硬编码的常量进行比较。

示例

基本格式用法

以下示例显示了如何使用英语创建相对时间格式化器。

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"

使用 auto 选项

如果传入了 numeric:auto 选项,它将生成字符串 yesterdaytodaytomorrow,而不是 1 day agoin 0 daysin 1 day。这使得输出不总是需要使用数值。

js
// Create a relative time formatter in your locale
// with numeric: "auto" option value passed in.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "yesterday"

rtf.format(0, "day"); // "today"

// Format relative time using positive day unit (1).
rtf.format(1, "day"); // "tomorrow"

规范

规范
ECMAScript® 2026 国际化 API 规范
# sec-Intl.RelativeTimeFormat.prototype.format

浏览器兼容性

另见