Temporal.PlainYearMonth.prototype.since()

可用性有限

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

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

since() 方法用于 Temporal.PlainYearMonth 实例,返回一个新的 Temporal.Duration 对象,表示从另一个可被 Temporal.PlainYearMonth.from() 转换的年-月到当前年-月的时间间隔。如果另一个月份早于当前月份,则间隔为正;如果晚于当前月份,则间隔为负。

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

语法

js
since(other)
since(other, options)

参数

其他

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

options 可选

一个包含 Temporal.Duration.prototype.round() 选项的对象,其中包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 只接受以下单位:“years”、“months”或它们的单数形式。对于 largestUnit,默认值 "auto" 表示 "years"。对于 smallestUnit,默认值为 "months"。当前日期用作 relativeTo 选项。

返回值

一个表示从 other 到当前年-月的时间间隔(since)的新的 Temporal.Duration 对象。如果 other 早于当前年-月,则间隔为正;如果晚于当前年-月,则间隔为负。

异常

RangeError

在以下情况之一中抛出

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

示例

使用 since()

js
const lastUpdated = Temporal.PlainYearMonth.from("2022-01");
const now = Temporal.Now.plainDateISO().toPlainYearMonth();
const duration = now.since(lastUpdated);
console.log(`Last updated ${duration.toLocaleString("en-US")} ago`);
// Expected output: "Last updated [number] years, [number] months ago"

const duration2 = now.since(lastUpdated, { largestUnit: "months" });
console.log(`Last updated ${duration2.toLocaleString("en-US")} ago`);
// Expected output: "Last updated [number] months ago"

const duration3 = now.since(lastUpdated, { smallestUnit: "years" });
console.log(`Last updated ${duration3.toLocaleString("en-US")} ago`);
// Expected output: "Last updated [number] years ago"

舍入结果

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

js
const ym1 = Temporal.PlainYearMonth.from("2022-01");
const ym2 = Temporal.PlainYearMonth.from("2022-11");
const duration = ym2.since(ym1, {
  smallestUnit: "years",
  roundingMode: "ceil",
});
console.log(duration.toString()); // "P1Y"

获取以天为单位的结果

默认情况下,结果间隔不包含天,因为 PlainYearMonth 不提供日级别精度。您可以通过先将其转换为具有明确日期的 Temporal.PlainDate 来以天为单位获取结果。

js
const ym1 = Temporal.PlainYearMonth.from("2022-01");
const ym2 = Temporal.PlainYearMonth.from("2022-11");
const duration = ym2.toPlainDate({ day: 1 }).since(ym1.toPlainDate({ day: 1 }));
console.log(duration.toString()); // "P304D"

规范

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

浏览器兼容性

另见