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

瀏覽器相容性

另見