Intl.RelativeTimeFormat.prototype.format() method formats a value and unit according to the locale and formatting options of this RelativeTimeFormat 对象。

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

relativeTimeFormat.format(value, unit)
					

参数

value

Numeric value to use in the internationalized relative time message.

unit
Unit to use in the relative time internationalized message. Possible values are: "year" , "quarter" , "month", "week", "day", "hour", "minute", "second" . Plural forms are also permitted.

描述

The function returned by the format getter formats a value and a unit into a string according to the locale and formatting options of this Intl.RelativeTimeFormat 对象。

范例

基本 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"
					

使用 auto option

numeric:auto option is passed, it will produce the string yesterday or tomorrow 而不是 1 day ago 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"
// Format relative time using positive day unit (1).
rtf.format(1, "day");
// > "tomorrow"
					

规范

规范 状态 注释
ECMAScript 国际化 API (ECMA-402)
The definition of 'RelativeTimeFormat.format()' in that specification.
Stage 4

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
format Chrome 71 Edge 79 Firefox 65 IE No Opera 58 Safari No WebView Android 71 Chrome Android 71 Firefox Android 65 Opera Android 50 Safari iOS No Samsung Internet Android 10.0 nodejs 12.0.0
12.0.0
Before version 13.0.0, only the locale data for en-US is available by default. See the RelativeTimeFormat() 构造函数 了解更多细节。

图例

完整支持

完整支持

不支持

不支持

见实现注意事项。

另请参阅

元数据

  • 最后修改: