语法
js
total(unit)
total(options)
参数
unit
-
一个字符串,表示
unit
选项。这是一个方便的重载,因此total(unit)
等同于total({ unit })
,其中unit
是一个字符串。 options
-
一个包含以下部分或全部属性的对象(按检索和验证的顺序):
relativeTo
可选-
一个带时区或不带时区的日期(时间),它提供时间与日历信息,用于解析 日历时长(有关此选项的通用解释,请参阅链接)。如果
this
或other
是日历时长,或者unit
是日历单位,则此选项是必需的。 unit
-
任何时间单位:
"years"
、"months"
、"weeks"
、"days"
、"hours"
、"minutes"
、"seconds"
、"milliseconds"
、"microseconds"
、"nanoseconds"
,或它们的单数形式。
返回值
一个浮点数,表示给定单位的总持续时间。由于浮点数精度限制,可能不精确。
异常
RangeError
-
在以下情况之一中抛出
- 未提供
unit
,或unit
不是有效单位。 this
或other
是日历时长,或者unit
是日历单位,并且未提供relativeTo
。
- 未提供
描述
如果提供了 relativeTo
,则结果的计算方法是将时长添加到起点,找出结果与起点之间的差值(以纳秒为单位),然后通过除以每单位的相应纳秒数将差值转换为所请求的单位。提供带时区的日期时间可以考虑夏令时和其他时区变化;否则,假定为 24 小时一天。
如果未提供 relativeTo
,则结果的计算方法是将时长转换为纳秒,然后除以每单位的相应纳秒数。
示例
使用 total()
js
const d = Temporal.Duration.from({ hours: 1, minutes: 30 });
console.log(d.total("minutes")); // 90
console.log(d.total("hours")); // 1.5
日历时长的总和
js
const d = Temporal.Duration.from({ months: 1 });
console.log(
d.total({ unit: "days", relativeTo: Temporal.PlainDate.from("2021-01-01") }),
); // 31
规范
规范 |
---|
Temporal # sec-temporal.duration.prototype.total |
浏览器兼容性
加载中…