Temporal.ZonedDateTime.prototype.since()
Temporal.ZonedDateTime 例項的 since() 方法返回一個新的 Temporal.Duration 物件,表示從另一個日期-時間(可透過 Temporal.ZonedDateTime.from() 轉換的形式)到當前日期-時間之間的持續時間。如果另一個日期-時間在此日期-時間之前,則持續時間為正;如果之後,則為負。
此方法執行 this - other。要執行 other - this,請使用 until() 方法。
語法
since(other)
since(other, options)
引數
其他-
一個字串、一個物件或一個
Temporal.ZonedDateTime例項,表示要從當前日期-時間中減去的日期-時間。它使用與Temporal.ZonedDateTime.from()相同的演算法轉換為Temporal.ZonedDateTime物件。它必須與this具有相同的日曆。 options可選-
一個物件,包含
Temporal.Duration.prototype.round()的選項,其中包括largestUnit、roundingIncrement、roundingMode和smallestUnit。largestUnit和smallestUnit接受所有可能的單位。對於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 小時。
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),則開始和結束必須在同一時區。
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 |
瀏覽器相容性
載入中…