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