Temporal.Duration.from()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

Temporal.Duration.from() 靜態方法可從另一個 Temporal.Duration 物件、一個具有時段屬性的物件或一個 ISO 8601 字串建立新的 Temporal.Duration 物件。

語法

js
Temporal.Duration.from(info)

引數

info

以下之一:

返回值

一個可能不平衡的新 Temporal.Duration 物件,具有指定的組成部分。

異常

RangeError

在以下情況之一中丟擲

  • info 物件中任何可識別的屬性不是整數(包括非有限值)。
  • 日曆單位(年、月、周)的絕對值 ≥ 232
  • 持續時間的非日曆部分(天及以下),以秒為單位表示時,其絕對值 ≥ 253
TypeError

在以下情況之一中丟擲

  • info 不是物件或字串。
  • info 物件中所有可識別的屬性都為 undefined

示例

從物件建立時段

js
const d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });
console.log(d1.toString()); // "PT1H30M"

const d2 = Temporal.Duration.from({ months: 1, days: 2 });
console.log(d2.toString()); // "P1M2D"

// Uncommon because unbalanced, but valid
const unbalanced = Temporal.Duration.from({
  hours: 100,
  minutes: 100,
  seconds: 100,
});
console.log(unbalanced.toString()); // "PT100H100M100S"

const neg = Temporal.Duration.from({ hours: -1, minutes: -30 });
console.log(neg.toString()); // "-PT1H30M"

從字串建立時段

js
const d = Temporal.Duration.from("P1Y2M3W4DT5H6M7.00800901S");
console.log(d.hours); // 5

從另一個時段建立時段

js
const d1 = Temporal.Duration.from({ hours: 1, minutes: 30 });
const d2 = Temporal.Duration.from(d1);
console.log(d2.toString()); // "PT1H30M"

規範

規範
Temporal
# sec-temporal.duration.from

瀏覽器相容性

另見