Temporal.PlainMonthDay.prototype.toLocaleString()
toLocaleString() 方法是 Temporal.PlainMonthDay 例項的一個方法,它返回一個代表該月-日的、符合語言習慣的字串。在支援 Intl.DateTimeFormat API 的實現中,此方法會委託給 Intl.DateTimeFormat。
每次呼叫 toLocaleString 時,它都必須在一個龐大的本地化字串資料庫中進行搜尋,這可能會效率低下。當該方法以相同的引數多次呼叫時,最好建立一個 Intl.DateTimeFormat 物件並使用其 format() 方法,因為 DateTimeFormat 物件會記住傳遞給它的引數,並可能決定快取資料庫的一部分,因此未來的 format 呼叫可以在更受限制的上下文中搜索本地化字串。
語法
toLocaleString()
toLocaleString(locales)
toLocaleString(locales, options)
引數
locales 和 options 引數自定義函式行為,並允許應用程式指定應使用的語言的格式約定。
在支援 Intl.DateTimeFormat API 的實現中,這些引數與 Intl.DateTimeFormat() 建構函式的引數完全對應。不支援 Intl.DateTimeFormat 的實現將返回與 toString() 完全相同的字串,並忽略這兩個引數。
locales可選-
一個帶有 BCP 47 語言標籤 的字串,或此類字串的陣列。對應於
Intl.DateTimeFormat()建構函式的locales引數。 options可選-
一個調整輸出格式的物件。對應於
Intl.DateTimeFormat()建構函式的options引數。calendar選項必須提供與此月-日日曆相同的值。關於 日期-時間元件選項 和樣式快捷方式(dateStyle和timeStyle),選項應遵循以下形式之一:- 不提供任何選項:
month和day將預設為"numeric"。 - 僅提供
dateStyle:它會擴充套件為month和day的格式。 - 提供一些日期-時間元件選項,其中至少有一個是
month或day。輸出中將僅包含指定的日期元件。
- 不提供任何選項:
有關這些引數及其使用方法的詳細資訊,請參閱 Intl.DateTimeFormat() 建構函式。
返回值
一個根據語言特定約定表示給定月-日的字串。
在支援 Intl.DateTimeFormat 的實現中,這等同於 new Intl.DateTimeFormat(locales, options).format(monthDay),其中 options 已經如上所述進行了規範化。
注意: 大多數情況下,toLocaleString() 返回的格式是一致的。然而,輸出在不同實現之間可能會有所不同,即使在相同的區域設定中也是如此——輸出差異是設計使然,並受規範允許。它也可能不符合您的預期。例如,字串可能使用不間斷空格或被雙向控制字元包圍。您不應將 toLocaleString() 的結果與硬編碼常量進行比較。
異常
RangeError-
如果任何選項無效,則丟擲。
TypeError-
如果任何選項的型別不符合預期,則丟擲。
示例
使用 toLocaleString()
不指定 locale 的此方法的簡單用法以預設區域設定和預設選項返回格式化字串。
// Note that just specifying "08-01" defaults to the ISO 8601 calendar,
// which throws an error if the locale's default calendar is not ISO 8601.
const md = Temporal.PlainMonthDay.from("2021-08-01[u-ca=gregory]");
console.log(md.toLocaleString()); // 8/1 (assuming en-US locale and Gregorian calendar)
如果月-日的日曆與區域設定的預設日曆不匹配,即使其日曆是 iso8601,也必須提供一個顯式的 calendar 選項,並賦予相同的值。
const md = Temporal.PlainMonthDay.from("08-01");
md.toLocaleString("en-US", { calendar: "iso8601" }); // 08-01
使用帶選項的 toLocaleString()
您可以透過提供 options 引數來自定義輸出中包含的月-日的哪些部分。
const md = Temporal.PlainMonthDay.from("2021-08-01[u-ca=gregory]");
md.toLocaleString("en-US", { dateStyle: "full" }); // August 1
md.toLocaleString("en-US", { month: "long" }); // August
md.toLocaleString("en-US", { day: "numeric" }); // 1
規範
| 規範 |
|---|
| Temporal # sec-temporal.plainmonthday.prototype.tolocalestring |
瀏覽器相容性
載入中…