Temporal.PlainDate.prototype.since()

可用性有限

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

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

since() 方法用于 Temporal.PlainDate 实例,它会返回一个新的 Temporal.Duration 对象,表示从另一个日期(可以通过 Temporal.PlainDate.from() 转换)到当前日期的时长。如果另一个日期早于当前日期,则时长为正;如果晚于当前日期,则时长为负。

此方法执行 this - other 操作。要执行 other - this,请使用 until() 方法。

语法

js
since(other)
since(other, options)

参数

其他

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

options 可选

一个包含 Temporal.Duration.prototype.round() 选项的对象,包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 只接受以下单位:“years”、“months”、“weeks”、“days”或其单数形式。对于 largestUnit,默认值 "auto" 表示 "days"smallestUnit,以较大者为准。对于 smallestUnit,默认值为 "days"。当前日期将用作 relativeTo 选项。请注意,使用 大于 "days" 的单位可能会导致时长无法移植到其他日历或日期。

返回值

一个新的 Temporal.Duration 对象,表示从 other 到当前日期的时长。如果 other 早于当前日期,则时长为正;如果晚于当前日期,则时长为负。

异常

RangeError

在以下情况之一中抛出

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

示例

使用 since()

js
const date = Temporal.PlainDate.from("2022-12-25");
const now = Temporal.Now.plainDateISO();
const duration = now.since(date);
const formatter = new Intl.DurationFormat("en-US", { style: "long" });
console.log(`It's been ${formatter.format(duration)} since that Christmas...`);
// Expected output: "It's been [number] days since that Christmas..."

const duration2 = now.since(date, { smallestUnit: "months" });
console.log(`It's been ${formatter.format(duration2)} since that Christmas...`);
// Expected output: "It's been [number] months since that Christmas..."

const duration3 = now.since(date, {
  largestUnit: "years",
  smallestUnit: "months",
});
console.log(`It's been ${formatter.format(duration3)} since that Christmas...`);
// Expected output: "It's been [number] years, [number] months since that Christmas..."

舍入结果

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

js
const date1 = Temporal.PlainDate.from("2022-01-01");
const date2 = Temporal.PlainDate.from("2022-01-28");
const duration = date2.since(date1, {
  smallestUnit: "days",
  roundingIncrement: 5,
  roundingMode: "ceil",
});
console.log(duration.toString()); // "P30D"

比较不同的日历

默认情况下,两个日期必须具有相同的日历。这是为了避免月份和年份含义上的歧义。如果您想比较来自不同日历的日期,可以先将它们转换为相同的日历。

js
const date1 = Temporal.PlainDate.from("2022-01-01");
const date2 = Temporal.PlainDate.from("2022-01-28[u-ca=chinese]");
const duration = date2.withCalendar("iso8601").since(date1);
console.log(duration.toString()); // "P27D"

规范

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

浏览器兼容性

另见