Temporal.ZonedDateTime.prototype.toLocaleString()
Temporal.ZonedDateTime 例項的 toLocaleString() 方法返回一個字串,該字串以語言敏感的方式表示此日期時間。在支援 Intl.DateTimeFormat API 的實現中,此方法會委託給 Intl.DateTimeFormat,並傳遞已轉換為 Temporal.Instant 的此日期時間(因為 Intl.DateTimeFormat 無法直接格式化 Temporal.ZonedDateTime)。
每次呼叫 toLocaleString 時,都必須在一個大型本地化字串資料庫中執行搜尋,這可能會效率低下。當該方法使用相同的引數多次呼叫時,最好建立一個 Intl.DateTimeFormat 物件並使用其 format() 方法,因為 DateTimeFormat 物件會記住傳遞給它的引數,並可能決定快取資料庫的一部分,因此未來的 format 呼叫可以在更受限制的上下文中搜索本地化字串。然而,目前 Intl.DateTimeFormat 不支援格式化 Temporal.ZonedDateTime 物件,因此在將其傳遞給 format() 之前,您必須先將其轉換為 Temporal.Instant 物件。
語法
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引數。如果此日期時間的日曆不是"iso8601",則必須提供具有相同值的calendar選項;否則,如果此日期時間的日曆是"iso8601",則calendar選項可以是任何值。不得提供timeZone選項,因為它會自動設定為此日期時間的timeZoneId。關於 日期時間元件選項 和樣式快捷方式(dateStyle和timeStyle),選項應遵循以下形式之一:- 不提供任何選項:
year、month、day、hour、minute和second將預設設定為"numeric"。 - 提供至少一個
dateStyle或timeStyle:日期時間元件將根據指定的樣式和區域設定進行設定。 - 提供一些日期時間元件選項。只有指定的日期時間元件將包含在輸出中。
- 不提供任何選項:
有關這些引數及其使用方法的詳細資訊,請參閱 Intl.DateTimeFormat() 建構函式。
返回值
一個字串,根據語言特定的約定表示給定的日期時間。
在具有 Intl.DateTimeFormat 的實現中,這等同於 new Intl.DateTimeFormat(locales, { ...options, timeZone: dateTime.timeZoneId }).format(dateTime.toInstant()),其中 options 已按上述方式規範化。
注意: 大多數情況下,toLocaleString() 返回的格式是一致的。然而,輸出在不同實現之間可能會有所不同,即使在相同的區域設定中也是如此——輸出差異是設計使然,並受規範允許。它也可能不符合您的預期。例如,字串可能使用不間斷空格或被雙向控制字元包圍。您不應將 toLocaleString() 的結果與硬編碼常量進行比較。
異常
RangeError-
如果任何選項無效,則丟擲。
TypeError-
如果任何選項的型別不符合預期,則丟擲。
示例
使用 toLocaleString()
不指定 locale 的此方法的簡單用法以預設區域設定和預設選項返回格式化字串。
const zdt = Temporal.ZonedDateTime.from(
"2021-08-01T12:34:56-04:00[America/New_York]",
);
console.log(zdt.toLocaleString()); // 8/1/2021, 12:34:56 PM EDT (assuming en-US locale)
如果日期的日曆與區域設定的預設日曆不匹配,並且日期的日曆不是 iso8601,則必須提供具有相同值的顯式 calendar 選項。
const zdt = Temporal.ZonedDateTime.from(
"2021-08-01T12:34:56+09:00[Asia/Tokyo][u-ca=japanese]",
);
// The ja-JP locale uses the Gregorian calendar by default
zdt.toLocaleString("ja-JP", { calendar: "japanese" }); // R3/8/1 12:34:56 JST
使用帶選項的 toLocaleString()
您可以透過提供 options 引數來自定義日期中包含在輸出中的部分。
const zdt = Temporal.ZonedDateTime.from(
"2021-08-01T12:34:56+09:00[Asia/Tokyo][u-ca=japanese]",
);
zdt.toLocaleString("ja-JP", {
calendar: "japanese",
dateStyle: "full",
timeStyle: "full",
}); // 令和3年8月1日日曜日 12時34分56秒 日本標準時
zdt.toLocaleString("ja-JP", {
calendar: "japanese",
year: "numeric",
month: "long",
hour: "numeric",
timeZoneName: "shortGeneric",
}); // 令和3年8月 12時 JST
zdt.toLocaleString("ja-JP", {
calendar: "japanese",
year: "numeric",
hour: "numeric",
minute: "numeric",
}); // 令和3年 12:34
規範
| 規範 |
|---|
| Temporal # sec-temporal.zoneddatetime.prototype.tolocalestring |
瀏覽器相容性
載入中…