Intl.RelativeTimeFormat.prototype.format()
Intl.RelativeTimeFormat 实例的 format() 方法根据此 Intl.RelativeTimeFormat 对象的区域设置和格式选项来格式化 value 和 unit。
¥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
语法
参数
返回值
¥Return value
表示给定 value 和 unit 的字符串,根据该 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 offormat()to hardcoded constants.
示例
基本格式使用
¥Basic format usage
以下示例演示如何使用英语创建相对时间格式化程序。
¥The following example shows how to create a relative time formatter using the English language.
// 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 选项,它将生成字符串 yesterday、today 或 tomorrow,而不是 1 day ago、in 0 days 或 in 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.
// 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 |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also