Temporal.PlainDateTime.prototype.since()

可用性有限

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

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

Temporal.PlainDateTime 例項的 since() 方法返回一個新的 Temporal.Duration 物件,表示從另一個日期時間(其形式可被 Temporal.PlainDateTime.from() 轉換)到此日期時間的時間差。如果另一個日期時間在此日期時間之前,則時間差為正值,反之為負值。

此方法執行 this - other 的計算。要執行 other - this,請使用 until() 方法。

語法

js
since(other)
since(other, options)

引數

其他

一個字串、物件或 Temporal.PlainDateTime 例項,表示要從此日期時間中減去的日期時間。它將使用與 Temporal.PlainDateTime.from() 相同的演算法轉換為 Temporal.PlainDateTime 物件。它的日曆必須與 this 相同。

options 可選

一個包含 Temporal.Duration.prototype.round() 選項的物件,其中包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 接受所有可能的單位。對於 largestUnit,預設值 "auto" 表示 "days"smallestUnit 中較大的一個。對於 smallestUnit,預設值為 "nanoseconds"。當前日期被用作 relativeTo 選項。請注意,使用大於 "days" 的單位可能會使持續時間無法移植到其他日曆或日期。

返回值

一個新的 Temporal.Duration 物件,表示 other 到此日期時間的時間差。如果 other 在此日期時間之前,則時間差為正值,反之為負值。

異常

RangeError

在以下情況之一中丟擲

  • other 的日曆與 this 不同。
  • 任何選項無效。

示例

使用 since()

js
let lastBilling = Temporal.PlainDateTime.from({
  year: Temporal.Now.plainDateISO().year,
  month: 4,
  day: 1,
});
const now = Temporal.Now.plainDateTimeISO().round("second");
if (Temporal.PlainDateTime.compare(lastBilling, now) > 0) {
  lastBilling = lastBilling.subtract({ years: 1 });
}
const duration = now.since(lastBilling);
console.log(`${duration.toLocaleString("en-US")} since last billing`);
// Expected output: "[number] days, [number] hr, [number] min, [number] sec since last billing"

const duration2 = now.since(lastBilling, { smallestUnit: "days" });
console.log(`${duration2.toLocaleString("en-US")} since last billing`);
// Expected output: "[number] days since last billing"

const duration3 = now.since(lastBilling, {
  largestUnit: "years",
  smallestUnit: "days",
});
console.log(`${duration3.toLocaleString("en-US")} since last billing`);
// Expected output: "[number] months, [number] days since last billing"

舍入結果

預設情況下,smallestUnit 的小數部分會被截斷。你可以使用 roundingIncrementroundingMode 選項對其進行舍入。

js
const dt1 = Temporal.PlainDateTime.from("2022-01-01T00:00:00");
const dt2 = Temporal.PlainDateTime.from("2022-01-28T12:34:56");
const duration = dt2.since(dt1, {
  smallestUnit: "days",
  roundingIncrement: 5,
  roundingMode: "ceil",
});
console.log(duration.toString()); // "P30D"

規範

規範
Temporal
# sec-temporal.plaindatetime.prototype.since

瀏覽器相容性

另見