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 |
浏览器兼容性
加载中…