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 |
瀏覽器相容性
載入中…