Temporal.PlainDateTime.prototype.since()
Temporal.PlainDateTime 实例的 since() 方法返回一个新的 Temporal.Duration 对象,表示从另一个日期时间(其形式可被 Temporal.PlainDateTime.from() 转换)到此日期时间的时间差。如果另一个日期时间在此日期时间之前,则时间差为正值,反之为负值。
此方法执行 this - other 的计算。要执行 other - this,请使用 until() 方法。
语法
since(other)
since(other, options)
参数
其他-
一个字符串、对象或
Temporal.PlainDateTime实例,表示要从此日期时间中减去的日期时间。它将使用与Temporal.PlainDateTime.from()相同的算法转换为Temporal.PlainDateTime对象。它的日历必须与this相同。 options可选-
一个包含
Temporal.Duration.prototype.round()选项的对象,其中包括largestUnit、roundingIncrement、roundingMode和smallestUnit。largestUnit和smallestUnit接受所有可能的单位。对于largestUnit,默认值"auto"表示"days"或smallestUnit中较大的一个。对于smallestUnit,默认值为"nanoseconds"。当前日期被用作relativeTo选项。请注意,使用大于"days"的单位可能会使持续时间无法移植到其他日历或日期。
返回值
一个新的 Temporal.Duration 对象,表示自 other 到此日期时间的时间差。如果 other 在此日期时间之前,则时间差为正值,反之为负值。
异常
RangeError-
在以下情况之一中抛出
other的日历与this不同。- 任何选项无效。
示例
使用 since()
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 的小数部分会被截断。你可以使用 roundingIncrement 和 roundingMode 选项对其进行舍入。
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 |
浏览器兼容性
加载中…