Temporal.PlainTime.prototype.since()

可用性有限

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

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

since() 方法用於 Temporal.PlainTime 例項,返回一個新的 Temporal.Duration 物件,表示從另一個可被 Temporal.PlainTime.from() 轉換的時間到此時間的時間差。如果另一個時間在當前時間之前,則時間差為正;如果在當前時間之後,則為負。

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

語法

js
since(other)
since(other, options)

引數

其他

一個字串、物件或 Temporal.PlainTime 例項,表示要從中減去的時間。它使用與 Temporal.PlainTime.from() 相同的演算法轉換為 Temporal.PlainTime 物件。

options 可選

包含 Temporal.Duration.prototype.round() 選項的物件,包括 largestUnitroundingIncrementroundingModesmallestUnitlargestUnitsmallestUnit 僅接受以下單位:“hours”、“minutes”、“seconds”、“milliseconds”、“microseconds”、“nanoseconds”或它們的單數形式。對於 largestUnit,預設值 "auto" 表示 "hours"。對於 smallestUnit,預設值為 "nanoseconds"

返回值

一個表示從 other 到此時間的時間差(since)的新的 Temporal.Duration 物件。如果 other 在此時間之前,則時間差為正;如果在此時間之後,則為負。

異常

RangeError

如果任何選項無效,則丟擲。

示例

使用 since()

js
const lunchTime = Temporal.PlainTime.from("12:30:00");
const now = Temporal.Now.plainTimeISO();
const duration = now.since(lunchTime);
console.log(`You had lunch ${duration.toLocaleString("en-US")} ago`);
// Example output: "You had lunch 3 hr, 42 min, 21 sec, 343 ms, 131 μs, 718 ns ago"

const duration2 = now.since(lunchTime, { smallestUnit: "minutes" });
console.log(`You had lunch ${duration2.toLocaleString("en-US")} ago`);
// Example output: "You had lunch 3 hr, 42 min ago"

const duration3 = now.since(lunchTime, {
  largestUnit: "minutes",
  smallestUnit: "minutes",
});
console.log(`You had lunch ${duration3.toLocaleString("en-US")} ago`);
// Example output: "You had lunch 222 min ago"

舍入結果

預設情況下,smallestUnit 的小數部分會被截斷。你可以使用 roundingIncrementroundingMode 選項對其進行舍入。

js
const time1 = Temporal.PlainTime.from("12:30:00");
const time2 = Temporal.PlainTime.from("12:30:01");
const duration = time2.since(time1, {
  smallestUnit: "seconds",
  roundingIncrement: 15,
  roundingMode: "ceil",
});
console.log(duration.toString()); // "PT15S"

規範

規範
Temporal
# sec-temporal.plaintime.prototype.since

瀏覽器相容性

另見