Temporal.PlainYearMonth.prototype.since()
since()
方法用于 Temporal.PlainYearMonth
实例,返回一个新的 Temporal.Duration
对象,表示从另一个可被 Temporal.PlainYearMonth.from()
转换的年-月到当前年-月的时间间隔。如果另一个月份早于当前月份,则间隔为正;如果晚于当前月份,则间隔为负。
此方法执行 this - other
。要执行 other - this
,请使用 until()
方法。
语法
since(other)
since(other, options)
参数
其他
-
一个字符串、对象或
Temporal.PlainYearMonth
实例,表示要从当前年-月减去的年-月。它使用与Temporal.PlainYearMonth.from()
相同的算法转换为Temporal.PlainYearMonth
对象。它必须与this
具有相同的日历。 options
可选-
一个包含
Temporal.Duration.prototype.round()
选项的对象,其中包括largestUnit
、roundingIncrement
、roundingMode
和smallestUnit
。largestUnit
和smallestUnit
只接受以下单位:“years
”、“months
”或它们的单数形式。对于largestUnit
,默认值"auto"
表示"years"
。对于smallestUnit
,默认值为"months"
。当前日期用作relativeTo
选项。
返回值
一个表示从 other
到当前年-月的时间间隔(since)的新的 Temporal.Duration
对象。如果 other
早于当前年-月,则间隔为正;如果晚于当前年-月,则间隔为负。
异常
RangeError
-
在以下情况之一中抛出
other
的日历与this
不同。- 任何选项无效。
示例
使用 since()
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
的小数部分会被截断。你可以使用 roundingIncrement
和 roundingMode
选项对其进行舍入。
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
来以天为单位获取结果。
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 |
浏览器兼容性
加载中…