Temporal.Instant.prototype.since()
since() 方法用於 例項,返回一個新的 Temporal.Instant 物件,表示從另一個可由 Temporal.Duration 轉換的即刻到此即刻的時間差。如果另一個即刻在此即刻之前,則時間差為正;如果在此即刻之後,則為負。Temporal.Instant.from()
此方法執行 this - other。要執行 other - this,請使用 方法。until()
語法
since(other)
since(other, options)
引數
其他-
一個字串或一個
例項,表示要從此即刻減去的時間點。它使用與Temporal.Instant相同的演算法轉換為Temporal.Instant.from()Temporal.Instant物件。 options可選-
一個包含
選項的物件,包括Temporal.Duration.prototype.round()largestUnit、roundingIncrement、roundingMode和smallestUnit。largestUnit和smallestUnit僅接受以下單位:"hours"、"minutes"、"seconds"、"milliseconds"、"microseconds"、"nanoseconds"或它們的單數形式。對於largestUnit,預設值"auto"表示"seconds"或smallestUnit,以較大的為準。對於smallestUnit,預設值為"nanoseconds"。
返回值
一個 新物件,表示從 Temporal.Durationother 到此即刻的 時間差。如果 other 在此即刻之前,則時間差為正;如果在此即刻之後,則為負。
異常
RangeError-
如果任何選項無效,則丟擲。
示例
使用 since()
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 方法對結果時長進行四捨五入。
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 |
瀏覽器相容性
載入中…