--- title: Intl.RelativeTimeFormat slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat translation_of: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat ---
Intl.RelativeTimeFormat
对象启用本地化的相对时间格式。
new Intl.RelativeTimeFormat([locales[, options]])
locales
可选的。带有BCP 47语言标记的字符串,或此类字符串的数组。有关参数的一般形式和解释locales
,请参阅{{jsxref("Global_Objects/Intl","Intl page","#Locale_identification_and_negotiation",1)}}。
options
localeMatcher
"lookup"
和"best fit"
; 默认是"best fit"
。有关此选项的信息,请参阅Intl
。numeric
"always"
(默认,例如,1 day ago
),"auto"
(例如yesterday
)。该"auto"
值允许不必总是在输出中使用数值。style
"long"
(默认,例如,in 1 month
)"short"
(例如in 1 mo.
),"narrow"
(例如in 1 mo.
)。狭窄的风格可能类似于某些语言环境的短风格。RelativeTimeFormat
实例RelativeTimeFormat
实例从其原型继承以下属性:
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat/prototype','Properties')}}
RelativeTimeFormat
实例从其原型继承以下方法:
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat/prototype','Methods')}}
format
用法以下示例显示如何使用英语创建相对时间格式化程序。
//在语言环境中创建相对时间格式化程序 //显式传入默认值。 const rtf = new Intl.RelativeTimeFormat("en",{ localeMatcher: "bestfit",//其他值:"lookup" numeric: "always",//其他值:"auto" style: "long",//其他值:"short"或"narrow" }); //使用负值(-1)格式化相对时间。 rtf.format(-1,"day"); //>"1 day ago" //使用正值(1)格式化相对时间。 rtf.format(1,"day"); //>"in 1 day"
auto
选项如果numeric:auto
选项被传递,它将生成字符串yesterday
或tomorrow
代替1 day ago
或in 1 day
。这允许不必总是在输出中使用数值。
//在语言环境中创建相对时间格式化程序 //使用数字:传入"auto"选项值。 const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"}); //使用负值(-1)格式化相对时间。 rtf.format(-1,"day"); //>"yesterday" //使用正日单位(1)格式化相对时间。 rtf.format(1,"day"); //>"tomorrow"
formatToParts
以下示例显示如何创建返回格式化部件的相对时间格式器
const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"}); //使用日期单位格式化相对时间。 rtf.formatToParts(-1,"day"); //> [{type: "literal",value: "yesterday"}] rtf.formatToParts(100,"day"); //> [{type: "literal",value: "in"}, //> {type: "integer",value: "100",unit: "day"}, //> {type: "literal",value: "days"}]
Specification | Status | Comment |
---|---|---|
Intl.RelativeTimeFormat Constructor | Stage 3 |