Temporal.PlainDate.prototype.since()

可用性有限

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

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

since() 方法用於 Temporal.PlainDate 例項,它會返回一個新的 Temporal.Duration 物件,表示從另一個日期(可以透過 Temporal.PlainDate.from() 轉換)到當前日期的時長。如果另一個日期早於當前日期,則時長為正;如果晚於當前日期,則時長為負。

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

語法

js
since(other)
since(other, options)

引數

其他

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

options 可選

一個包含 Temporal.Duration.prototype.round() 選項的物件,包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 只接受以下單位:“years”、“months”、“weeks”、“days”或其單數形式。對於 largestUnit,預設值 "auto" 表示 "days"smallestUnit,以較大者為準。對於 smallestUnit,預設值為 "days"。當前日期將用作 relativeTo 選項。請注意,使用 大於 "days" 的單位可能會導致時長無法移植到其他日曆或日期。

返回值

一個新的 Temporal.Duration 物件,表示從 other 到當前日期的時長。如果 other 早於當前日期,則時長為正;如果晚於當前日期,則時長為負。

異常

RangeError

在以下情況之一中丟擲

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

示例

使用 since()

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

js
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"

比較不同的日曆

預設情況下,兩個日期必須具有相同的日曆。這是為了避免月份和年份含義上的歧義。如果您想比較來自不同日曆的日期,可以先將它們轉換為相同的日曆。

js
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

瀏覽器相容性

另見