Temporal.Duration.prototype.toLocaleString()
toLocaleString()
方法用于
实例,返回该持续时间的、符合语言习惯的表示形式的字符串。在支持 Temporal.Duration
Intl.DurationFormat API
的实现中,此方法会委托给 Intl.DurationFormat
。
每次调用 toLocaleString
时,都需要在一个大型的本地化字符串数据库中进行搜索,这可能会效率低下。当多次使用相同参数调用该方法时,最好创建一个 Intl.DurationFormat
对象并使用其 format()
方法,因为 DurationFormat
对象会记住传递给它的参数,并可能决定缓存数据库的一部分,这样未来的 format
调用就可以在一个更受限的上下文中搜索本地化字符串。
语法
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
参数
locales
和 options
参数自定义函数行为,并允许应用程序指定应使用的语言的格式约定。
在支持 Intl.DurationFormat API
的实现中,这些参数与 Intl.DurationFormat()
构造函数的参数完全对应。不支持 Intl.DurationFormat
的实现将返回与 toString()
完全相同的字符串,并忽略这两个参数。
locales
可选-
一个包含 BCP 47 语言标签 的字符串,或者这些字符串的数组。对应于
Intl.DurationFormat()
构造函数的locales
参数。 options
可选-
一个调整输出格式的对象。对应于
Intl.DurationFormat()
构造函数的options
参数。
有关这些参数的详细信息以及如何使用它们,请参阅 Intl.DurationFormat()
构造函数。
返回值
一个表示给定持续时间的字符串,符合语言的特定约定。
在支持 Intl.DurationFormat
的实现中,这等效于 new Intl.DurationFormat(locales, options).format(duration)
。
注意: 大多数情况下,toLocaleString()
返回的格式是一致的。然而,输出在不同实现之间可能会有所不同,即使在相同的区域设置中也是如此——输出差异是设计使然,并受规范允许。它也可能不符合您的预期。例如,字符串可能使用不间断空格或被双向控制字符包围。您不应将 toLocaleString()
的结果与硬编码常量进行比较。
示例
使用 toLocaleString()
不指定 locale
的此方法的简单用法以默认区域设置和默认选项返回格式化字符串。
const duration = Temporal.Duration.from({ hours: 1, minutes: 30, seconds: 15 });
console.log(duration.toLocaleString()); // 1 hr, 30 min, 15 sec
规范
规范 |
---|
Temporal # sec-temporal.duration.prototype.tolocalestring |
浏览器兼容性
加载中…