Temporal.Duration.prototype.toLocaleString()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

toLocaleString() 方法用於 Temporal.Duration 例項,返回該持續時間的、符合語言習慣的表示形式的字串。在支援 Intl.DurationFormat API 的實現中,此方法會委託給 Intl.DurationFormat

每次呼叫 toLocaleString 時,都需要在一個大型的本地化字串資料庫中進行搜尋,這可能會效率低下。當多次使用相同引數呼叫該方法時,最好建立一個 Intl.DurationFormat 物件並使用其 format() 方法,因為 DurationFormat 物件會記住傳遞給它的引數,並可能決定快取資料庫的一部分,這樣未來的 format 呼叫就可以在一個更受限的上下文中搜索本地化字串。

語法

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

引數

localesoptions 引數自定義函式行為,並允許應用程式指定應使用的語言的格式約定。

在支援 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 的此方法的簡單用法以預設區域設定和預設選項返回格式化字串。

js
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

瀏覽器相容性

另見