Temporal.PlainDateTime.prototype.since()

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

Temporal.PlainDateTime 实例的 since() 方法返回一个新的 Temporal.Duration 对象,表示从另一个日期时间(其形式可被 Temporal.PlainDateTime.from() 转换)到此日期时间的时间差。如果另一个日期时间在此日期时间之前,则时间差为正值,反之为负值。

此方法执行 this - other 的计算。要执行 other - this,请使用 until() 方法。

语法

js
since(other)
since(other, options)

参数

其他

一个字符串、对象或 Temporal.PlainDateTime 实例,表示要从此日期时间中减去的日期时间。它将使用与 Temporal.PlainDateTime.from() 相同的算法转换为 Temporal.PlainDateTime 对象。它的日历必须与 this 相同。

options 可选

一个包含 Temporal.Duration.prototype.round() 选项的对象,其中包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 接受所有可能的单位。对于 largestUnit,默认值 "auto" 表示 "days"smallestUnit 中较大的一个。对于 smallestUnit,默认值为 "nanoseconds"。当前日期被用作 relativeTo 选项。请注意,使用大于 "days" 的单位可能会使持续时间无法移植到其他日历或日期。

返回值

一个新的 Temporal.Duration 对象,表示 other 到此日期时间的时间差。如果 other 在此日期时间之前,则时间差为正值,反之为负值。

异常

RangeError

在以下情况之一中抛出

  • other 的日历与 this 不同。
  • 任何选项无效。

示例

使用 since()

js
let lastBilling = Temporal.PlainDateTime.from({
  year: Temporal.Now.plainDateISO().year,
  month: 4,
  day: 1,
});
const now = Temporal.Now.plainDateTimeISO().round("second");
if (Temporal.PlainDateTime.compare(lastBilling, now) > 0) {
  lastBilling = lastBilling.subtract({ years: 1 });
}
const duration = now.since(lastBilling);
console.log(`${duration.toLocaleString("en-US")} since last billing`);
// Expected output: "[number] days, [number] hr, [number] min, [number] sec since last billing"

const duration2 = now.since(lastBilling, { smallestUnit: "days" });
console.log(`${duration2.toLocaleString("en-US")} since last billing`);
// Expected output: "[number] days since last billing"

const duration3 = now.since(lastBilling, {
  largestUnit: "years",
  smallestUnit: "days",
});
console.log(`${duration3.toLocaleString("en-US")} since last billing`);
// Expected output: "[number] months, [number] days since last billing"

舍入结果

默认情况下,smallestUnit 的小数部分会被截断。你可以使用 roundingIncrementroundingMode 选项对其进行舍入。

js
const dt1 = Temporal.PlainDateTime.from("2022-01-01T00:00:00");
const dt2 = Temporal.PlainDateTime.from("2022-01-28T12:34:56");
const duration = dt2.since(dt1, {
  smallestUnit: "days",
  roundingIncrement: 5,
  roundingMode: "ceil",
});
console.log(duration.toString()); // "P30D"

规范

规范
Temporal
# sec-temporal.plaindatetime.prototype.since

浏览器兼容性

另见