Temporal.Instant.prototype.since()

可用性有限

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

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

since() 方法用於 Temporal.Instant 例項,返回一個新的 Temporal.Duration 物件,表示從另一個可由 Temporal.Instant.from() 轉換的即刻到此即刻的時間差。如果另一個即刻在此即刻之前,則時間差為正;如果在此即刻之後,則為負。

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

語法

js
since(other)
since(other, options)

引數

其他

一個字串或一個 Temporal.Instant 例項,表示要從此即刻減去的時間點。它使用與 Temporal.Instant.from() 相同的演算法轉換為 Temporal.Instant 物件。

options 可選

一個包含 Temporal.Duration.prototype.round() 選項的物件,包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 僅接受以下單位:"hours""minutes""seconds""milliseconds""microseconds""nanoseconds" 或它們的單數形式。對於 largestUnit,預設值 "auto" 表示 "seconds"smallestUnit,以較大的為準。對於 smallestUnit,預設值為 "nanoseconds"

返回值

一個 Temporal.Duration 新物件,表示從 other 到此即刻的 時間差。如果 other 在此即刻之前,則時間差為正;如果在此即刻之後,則為負。

異常

RangeError

如果任何選項無效,則丟擲。

示例

使用 since()

js
const lastUpdated = Temporal.Instant.fromEpochMilliseconds(1735235418000);
const now = Temporal.Now.instant();
const duration = now.since(lastUpdated, { smallestUnit: "minute" });
console.log(`Last updated ${duration.toLocaleString("en-US")} ago`);

平衡結果時長

由於即刻不包含日曆資訊,因此生成的時間差避免了 日曆時長(如果沒有日曆和時間參考,這些時長會變得模糊)。因此,結果是 不平衡 的,因為 hours 可能大於 24。要平衡時長,請使用帶有日曆資訊的 relativeTo,再次使用 round 方法對結果時長進行四捨五入。

js
const lastUpdated = Temporal.Instant.fromEpochMilliseconds(1735235418000);
const now = Temporal.Now.instant();
const duration = now.since(lastUpdated, { smallestUnit: "minutes" });
const roundedDuration = duration.round({
  largestUnit: "years",
  // Use the ISO calendar; you can convert to another calendar using
  // withCalendar()
  relativeTo: now.toZonedDateTimeISO("UTC"),
});
console.log(`Last updated ${roundedDuration.toLocaleString("en-US")} ago`);

規範

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

瀏覽器相容性

另見