Temporal.ZonedDateTime.prototype.since()

可用性有限

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

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

Temporal.ZonedDateTime 例項的 since() 方法返回一個新的 Temporal.Duration 物件,表示從另一個日期-時間(可透過 Temporal.ZonedDateTime.from() 轉換的形式)到當前日期-時間之間的持續時間。如果另一個日期-時間在此日期-時間之前,則持續時間為正;如果之後,則為負。

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

語法

js
since(other)
since(other, options)

引數

其他

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

options 可選

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

返回值

一個表示從 other 到當前日期-時間的持續時間的新 Temporal.Duration 物件。如果 other 在此日期-時間之前,則持續時間為正;如果之後,則為負。

異常

RangeError

在以下情況之一中丟擲

  • other 的日曆與 this 不同。
  • 任何選項無效。
  • other 的時區與 this 不同,並且 largestUnit"days" 或以上。

描述

返回的持續時間是“混合”持續時間。這意味著持續時間的日期部分表示完整日曆日,就像 Temporal.PlainDateTime.prototype.since() 返回的那樣,而其時間部分表示實際經過的時間,就像 Temporal.Instant.prototype.since() 返回的那樣。這種“混合持續時間”方法會自動調整夏令時,並符合廣泛採用的行業標準,例如 RFC 5545 (iCalendar)。請參閱下面的示例。

示例

偏移轉換

發生轉換時,一天可能不正好是 24 小時。

js
const start = Temporal.ZonedDateTime.from(
  "2024-11-03T01:00:00-04:00[America/New_York]",
);
const end = Temporal.ZonedDateTime.from(
  "2024-11-04T01:00:00-05:00[America/New_York]",
);
console.log(end.since(start).toString()); // PT25H
console.log(end.since(start, { largestUnit: "days" }).toString()); // PT1D

const start2 = Temporal.ZonedDateTime.from(
  "2024-03-10T01:00:00-05:00[America/New_York]",
);
const end2 = Temporal.ZonedDateTime.from(
  "2024-03-11T01:00:00-04:00[America/New_York]",
);
console.log(end2.since(start2).toString()); // PT23H
console.log(end2.since(start2, { largestUnit: "days" }).toString()); // PT1D

因此,預設情況下,返回的持續時間純粹是基於時間的,沒有日期部分,以便保持明確性。

不同的時區

返回持續時間的時間部分純粹基於即時時間,不受時區影響。但是,如果您想包含任何日期單位(如 day),則開始和結束必須在同一時區。

js
const start = Temporal.ZonedDateTime.from(
  "2024-11-03T01:00:00-04:00[America/New_York]",
);
// Peru does not use DST so its offset remains -05:00 year-round
const end = Temporal.ZonedDateTime.from(
  "2024-11-04T01:00:00-05:00[America/Lima]",
);

end.since(start); // PT25H
end.since(start, { largestUnit: "days" }); // RangeError: time zones "America/Lima" and "America/New_York" aren't compatible

end.withTimeZone("America/New_York").since(start, { largestUnit: "days" }); // P1D
end.since(start.withTimeZone("America/Lima"), { largestUnit: "days" }); // P1D1H

有關如何使用 since() 的更多示例,尤其是舍入,請參閱 Temporal.PlainDate.prototype.since()Temporal.PlainTime.prototype.since()

規範

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

瀏覽器相容性

另見