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 |
浏览器兼容性
加载中…