Temporal.PlainYearMonth.prototype.toLocaleString()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

toLocaleString() 方法用于 Temporal.PlainYearMonth 实例,返回一个表示此年月(year-month)的、符合语言习惯的字符串。在支持 Intl.DateTimeFormat API 的实现中,此方法会委托给 Intl.DateTimeFormat

每次调用 toLocaleString 时,它都必须在一个庞大的本地化字符串数据库中进行搜索,这可能会效率低下。当该方法以相同的参数多次调用时,最好创建一个 Intl.DateTimeFormat 对象并使用其 format() 方法,因为 DateTimeFormat 对象会记住传递给它的参数,并可能决定缓存数据库的一部分,因此未来的 format 调用可以在更受限制的上下文中搜索本地化字符串。

语法

js
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)

参数

localesoptions 参数自定义函数行为,并允许应用程序指定应使用的语言的格式约定。

在支持 Intl.DateTimeFormat API 的实现中,这些参数与 Intl.DateTimeFormat() 构造函数的参数完全对应。不支持 Intl.DateTimeFormat 的实现将返回与 toString() 完全相同的字符串,并忽略这两个参数。

locales 可选

一个带有 BCP 47 语言标签 的字符串,或此类字符串的数组。对应于 Intl.DateTimeFormat() 构造函数的 locales 参数。

options 可选

一个调整输出格式的对象。对应于 Intl.DateTimeFormat() 构造函数的 options 参数。calendar 选项必须提供与此年月相同的日历值。关于 日期时间组件选项 和样式快捷方式(dateStyletimeStyle),选项应遵循以下形式之一:

  • 不提供任何选项:yearmonth 将默认为 "numeric"
  • 仅提供 dateStyle:它会扩展为 erayearmonth 格式。
  • 提供一些日期时间组件选项,其中至少有一个是 yearmonth。输出中将仅包含指定的日期组件。

有关这些参数及其使用方法的详细信息,请参阅 Intl.DateTimeFormat() 构造函数

返回值

一个根据语言特定约定表示给定年月(year-month)的字符串。

在支持 Intl.DateTimeFormat 的实现中,这等同于 new Intl.DateTimeFormat(locales, options).format(yearMonth),其中 options 已按上述方式进行了规范化。

注意: 大多数情况下,toLocaleString() 返回的格式是一致的。然而,输出在不同实现之间可能会有所不同,即使在相同的区域设置中也是如此——输出差异是设计使然,并受规范允许。它也可能不符合您的预期。例如,字符串可能使用不间断空格或被双向控制字符包围。您不应将 toLocaleString() 的结果与硬编码常量进行比较。

异常

RangeError

如果任何选项无效,则抛出。

TypeError

如果任何选项的类型不符合预期,则抛出。

示例

使用 toLocaleString()

不指定 locale 的此方法的简单用法以默认区域设置和默认选项返回格式化字符串。

js
// Note that just specifying "2021-08" defaults to the ISO 8601 calendar,
// which throws an error if the locale's default calendar is not ISO 8601.
const ym = Temporal.PlainYearMonth.from("2021-08-01[u-ca=gregory]");

console.log(ym.toLocaleString()); // 8/2021 (assuming en-US locale and Gregorian calendar)

如果此年月的日历与区域设置的默认日历不匹配,即使其日历是 iso8601,也必须提供一个显式的 calendar 选项,并具有相同的值。

js
const ym = Temporal.PlainYearMonth.from("2021-08");
ym.toLocaleString("en-US", { calendar: "iso8601" }); // 2021-08

使用带选项的 toLocaleString()

您可以通过提供 options 参数来定制输出中包含的年月(year-month)部分。

js
const ym = Temporal.PlainYearMonth.from("2021-08-01[u-ca=gregory]");
ym.toLocaleString("en-US", { dateStyle: "full" }); // August 2021
ym.toLocaleString("en-US", { year: "2-digit" }); // 21
ym.toLocaleString("en-US", { month: "long" }); // August

规范

规范
Temporal
# sec-temporal.plainyearmonth.prototype.tolocalestring

浏览器兼容性

另见