Temporal.PlainDate.prototype.since()
since()
方法用于 Temporal.PlainDate
实例,它会返回一个新的 Temporal.Duration
对象,表示从另一个日期(可以通过 Temporal.PlainDate.from()
转换)到当前日期的时长。如果另一个日期早于当前日期,则时长为正;如果晚于当前日期,则时长为负。
此方法执行 this - other
操作。要执行 other - this
,请使用 until()
方法。
语法
since(other)
since(other, options)
参数
其他
-
一个表示要从当前日期中减去的日期的字符串、对象或
Temporal.PlainDate
实例。它将使用与Temporal.PlainDate.from()
相同的算法转换为Temporal.PlainDate
对象。它必须与this
具有相同的日历。 options
可选-
一个包含
Temporal.Duration.prototype.round()
选项的对象,包括largestUnit
、roundingIncrement
、roundingMode
和smallestUnit
。largestUnit
和smallestUnit
只接受以下单位:“years”、“months”、“weeks”、“days”或其单数形式。对于largestUnit
,默认值"auto"
表示"days"
或smallestUnit
,以较大者为准。对于smallestUnit
,默认值为"days"
。当前日期将用作relativeTo
选项。请注意,使用 大于"days"
的单位可能会导致时长无法移植到其他日历或日期。
返回值
一个新的 Temporal.Duration
对象,表示从 other
到当前日期的时长。如果 other
早于当前日期,则时长为正;如果晚于当前日期,则时长为负。
异常
RangeError
-
在以下情况之一中抛出
other
的日历与this
不同。- 任何选项无效。
示例
使用 since()
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
的小数部分会被截断。你可以使用 roundingIncrement
和 roundingMode
选项对其进行舍入。
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"
比较不同的日历
默认情况下,两个日期必须具有相同的日历。这是为了避免月份和年份含义上的歧义。如果您想比较来自不同日历的日期,可以先将它们转换为相同的日历。
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 |
浏览器兼容性
加载中…