Temporal.Duration.prototype.add()
add() 方法 Temporal.Duration 例項會返回一個新的 Temporal.Duration 物件,該物件是此持續時間和給定持續時間的總和。結果是平衡的。
語法
js
add(other)
引數
其他-
一個字串、一個物件或一個
Temporal.Duration例項,表示要新增到此持續時間中的持續時間。它使用與Temporal.Duration.from()相同的演算法轉換為Temporal.Duration物件。
返回值
一個代表此持續時間和 other 總和的新 Temporal.Duration 物件。
異常
RangeError-
在以下情況之一中丟擲
this或other是日曆持續時間(它具有非零的years、months或weeks),因為在沒有日曆和時間參考的情況下,日曆持續時間是不明確的。this和other的總和超過了可表示持續時間的最大值或低於最小值,即 ±253 秒。
描述
非日曆持續時間明確地表示固定時間量。在內部,this 和 other 都被轉換為納秒(假設一天為 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 |
瀏覽器相容性
載入中…