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

浏览器兼容性

另见