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的值為0、3、6、9。如果指定了此選項,則會忽略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 |
瀏覽器相容性
載入中…