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