Intl.RelativeTimeFormat.prototype.format()

Intl.RelativeTimeFormat 实例的 format() 方法根据此 Intl.RelativeTimeFormat 对象的区域设置和格式选项来格式化 valueunit

¥The format() method of Intl.RelativeTimeFormat instances formats a value and unit according to the locale and formatting options of this Intl.RelativeTimeFormat object.

Try it

语法

¥Syntax

js
format(value, unit)

参数

¥Parameters

value

在国际化相对时间消息中使用的数值。

unit

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

返回值

¥Return value

表示给定 valueunit 的字符串,根据该 Intl.RelativeTimeFormat 对象的区域设置和格式选项进行格式化。

¥A string representing the given value and unit formatted according to the locale and formatting options of this Intl.RelativeTimeFormat object.

注意:大多数时候,format() 返回的格式是一致的。但是,即使在同一语言环境中,输出也可能因实现而异 - 输出变化是设计使然,并且规范允许。它也可能不是你所期望的。例如,字符串可以使用不间断空格或被双向控制字符包围。你不应该将 format() 的结果与硬编码常量进行比较。

¥Note: Most of the time, the formatting returned by format() is consistent. However, the output may vary between implementations, even within the same locale — output variations are by design and allowed by the specification. It may also not be what you expect. For example, the string may use non-breaking spaces or be surrounded by bidirectional control characters. You should not compare the results of format() to hardcoded constants.

示例

¥Examples

基本格式使用

¥Basic format usage

以下示例演示如何使用英语创建相对时间格式化程序。

¥The following example shows how to create a relative time formatter using the English language.

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"

使用自动选项

¥Using the auto option

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

¥If numeric:auto option is passed, it will produce the string yesterday, today, or tomorrow instead of 1 day ago, in 0 days, or in 1 day. This allows to not always have to use numeric values in the output.

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"

规范

Specification
ECMAScript Internationalization API Specification
# sec-Intl.RelativeTimeFormat.prototype.format

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看