Temporal.Duration.prototype.add()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

add() 方法 Temporal.Duration 实例会返回一个新的 Temporal.Duration 对象,该对象是此持续时间和给定持续时间的总和。结果是平衡的

语法

js
add(other)

参数

其他

一个字符串、一个对象或一个 Temporal.Duration 实例,表示要添加到此持续时间中的持续时间。它使用与 Temporal.Duration.from() 相同的算法转换为 Temporal.Duration 对象。

返回值

一个代表此持续时间和 other 总和的新 Temporal.Duration 对象。

异常

RangeError

在以下情况之一中抛出

  • thisother日历持续时间(它具有非零的 yearsmonthsweeks),因为在没有日历和时间参考的情况下,日历持续时间是不明确的。
  • thisother 的总和超过了可表示持续时间的最大值或低于最小值,即 ±253 秒。

描述

非日历持续时间明确地表示固定时间量。在内部,thisother 都被转换为纳秒(假设一天为 24 小时)并相加。然后将结果转换回 Temporal.Duration 对象,因此结果始终是平衡的或顶部重的,其中最大的单位是 days

如果要执行日历持续时间的加减法,可以将两个持续时间添加到起点,然后确定两个结果瞬间之间的差值;也就是说,dur1 + dur2 等同于 (start + dur1 + dur2) - start

要将持续时间添加到日期或时间,请改用日期或时间对象的 add() 方法。

示例

使用 add()

js
const d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });
const d2 = Temporal.Duration.from({ hours: -1, minutes: -20 });

const d3 = d1.add(d2);
console.log(d3.toString()); // "PT10M"

添加日历持续时间

js
const d1 = Temporal.Duration.from({ days: 1 });
const d2 = Temporal.Duration.from({ months: 1 });

d1.add(d2); // RangeError: for calendar duration arithmetic, use date arithmetic relative to a starting point

const start = Temporal.PlainDateTime.from("2022-01-01T00:00"); // ISO 8601 calendar
const result = start.add(d1).add(d2).since(start);
console.log(result.toString()); // "P32D"

规范

规范
Temporal
# sec-temporal.duration.prototype.add

浏览器兼容性

另见