Temporal.Duration.prototype.toString()

可用性有限

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

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

toString() 方法是 Temporal.Duration 例項上的一個方法,它會返回一個以 ISO 8601 格式 表示該持續時間的字串。

語法

js
toString()
toString(options)

引數

options 可選

一個包含以下部分或全部屬性的物件(按檢索和驗證的順序):

fractionalSecondDigits 可選

一個 0 到 9 之間的整數,或字串 "auto"。預設值為 "auto"。如果為 "auto",則從小數秒中刪除尾隨零。否則,秒元件的小數部分包含這麼多位數,必要時用零填充或四捨五入。

roundingMode 可選

一個字串,指定如何對超出 fractionalSecondDigits 的小數秒位數進行四捨五入。請參閱 Intl.NumberFormat()。預設為 "trunc"

smallestUnit 可選

一個字串,指定要在輸出中包含的最小單位。可能的值是 "second""millisecond""microsecond""nanosecond",或者它們的複數形式,它們分別等同於 fractionalSecondDigits 的值為 0369。如果指定了此選項,則會忽略 fractionalSecondDigits

返回值

一個字串,以 ISO 8601 格式 表示給定的持續時間,並根據選項格式化亞秒部分。零持續時間表示為 "PT0S"

異常

RangeError

如果任何選項無效,則丟擲。

示例

使用 toString()

js
const duration = Temporal.Duration.from({ hours: 1, minutes: 30, seconds: 15 });
console.log(duration.toString()); // 'PT1H30M15S'

// Stringification implicitly calls toString()
console.log(`${duration}`); // 'PT1H30M15S'

使用選項

js
const worldRecord = Temporal.Duration.from({ seconds: 9, milliseconds: 580 });
console.log(worldRecord.toString()); // 'PT9.58S'
console.log(worldRecord.toString({ fractionalSecondDigits: 1 })); // 'PT9.5S'
console.log(worldRecord.toString({ fractionalSecondDigits: 0 })); // 'PT9S'
console.log(worldRecord.toString({ smallestUnit: "millisecond" })); // 'PT9.580S'
console.log(
  worldRecord.toString({
    fractionalSecondDigits: 1,
    roundingMode: "halfExpand",
  }),
); // 'PT9.6S'

規範

規範
Temporal
# sec-temporal.duration.prototype.tostring

瀏覽器相容性

另見