Temporal.PlainYearMonth.prototype.since()

可用性有限

此特性不是基線特性,因為它在一些最廣泛使用的瀏覽器中不起作用。

實驗性: 這是一項實驗性技術
在生產中使用此技術之前,請仔細檢查瀏覽器相容性表格

since() 方法用於 Temporal.PlainYearMonth 例項,返回一個新的 Temporal.Duration 物件,表示從另一個可被 Temporal.PlainYearMonth.from() 轉換的年-月到當前年-月的時間間隔。如果另一個月份早於當前月份,則間隔為正;如果晚於當前月份,則間隔為負。

此方法執行 this - other。要執行 other - this,請使用 until() 方法。

語法

js
since(other)
since(other, options)

引數

其他

一個字串、物件或 Temporal.PlainYearMonth 例項,表示要從當前年-月減去的年-月。它使用與 Temporal.PlainYearMonth.from() 相同的演算法轉換為 Temporal.PlainYearMonth 物件。它必須與 this 具有相同的日曆。

options 可選

一個包含 Temporal.Duration.prototype.round() 選項的物件,其中包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 只接受以下單位:“years”、“months”或它們的單數形式。對於 largestUnit,預設值 "auto" 表示 "years"。對於 smallestUnit,預設值為 "months"。當前日期用作 relativeTo 選項。

返回值

一個表示從 other 到當前年-月的時間間隔(since)的新的 Temporal.Duration 物件。如果 other 早於當前年-月,則間隔為正;如果晚於當前年-月,則間隔為負。

異常

RangeError

在以下情況之一中丟擲

  • other 的日曆與 this 不同。
  • 任何選項無效。

示例

使用 since()

js
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 的小數部分會被截斷。你可以使用 roundingIncrementroundingMode 選項對其進行舍入。

js
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 來以天為單位獲取結果。

js
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

瀏覽器相容性

另見