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
"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 |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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
|
完整支持
不支持
见实现注意事项。
Intl
Collator
DateTimeFormat
ListFormat
NumberFormat
PluralRules
RelativeTimeFormat
Object
Object.prototype.__defineGetter__()
Object.prototype.__defineSetter__()
Object.prototype.__lookupGetter__()
Object.prototype.__lookupSetter__()
Object.prototype.hasOwnProperty()
Object.prototype.isPrototypeOf()
Object.prototype.propertyIsEnumerable()
Object.prototype.toLocaleString()
Object.prototype.toSource()
Object.prototype.toString()
Object.prototype.valueOf()
Object.setPrototypeOf()