Temporal.PlainDateTime.prototype.with()

可用性有限

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

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

Temporal.PlainDateTime 例項的 with() 方法返回一個新的 Temporal.PlainDateTime 物件,該物件表示此日期-時間,其中一些欄位已替換為新值。由於所有 Temporal 物件都被設計為不可變,因此此方法實質上充當日期-時間欄位的設定器。

要替換 calendarId 屬性,請改用 withCalendar() 方法。

語法

js
with(info)
with(info, options)

引數

info

一個物件,包含 Temporal.PlainDateTime.from() 識別的至少一個屬性(calendar 除外):dayeraeraYearhourmicrosecondmillisecondminutemonthmonthCodenanosecondsecondyear。未指定的屬性使用原始日期-時間的值。你只需提供 monthmonthCode 中的一個,以及 eraeraYearyear 中的一個,另一個將相應更新。

options 可選

包含以下屬性的物件

overflow 可選

一個字串,指定日期元件超出範圍時的行為。可能的值是

"constrain"(預設)

日期元件被限制在有效範圍內。

"reject"

如果日期元件超出範圍,則丟擲 RangeError

返回值

一個新的 Temporal.PlainDateTime 物件,其中 info 中指定的非 undefined 欄位被替換為相應的值,其餘欄位從原始日期-時間複製。

異常

TypeError

在以下情況之一中丟擲

  • info 不是一個物件。
  • options 不是物件或 undefined
RangeError

在以下情況之一中丟擲

  • 指定相同元件的提供的屬性不一致。
  • 提供的非數字屬性無效;例如,如果 monthCode 在此日曆中從未是有效的月份程式碼。
  • 提供的數字屬性超出範圍,並且 options.overflow 設定為 "reject"
  • 結果不在可表示範圍內,該範圍是距 Unix 紀元 ±(108 + 1) 天,約 ±273,972.6 年。

示例

使用 with()

js
const dt = Temporal.PlainDateTime.from("2021-07-01T12:34:56");
const newDT = dt.with({ hour: 13 });
console.log(newDT.toString()); // "2021-07-01T13:34:56"
const newDT2 = dt.with({ month: 2, day: 22, millisecond: 222 });
console.log(newDT2.toString()); // "2021-02-22T13:34:56.222"
const nextDecade = dt.with({ year: dt.year + 10 });
console.log(nextDecade.toString()); // "2031-07-01T13:34:56"

有關更多示例,請參閱可以使用 with() 設定的各個屬性的文件。

規範

規範
Temporal
# sec-temporal.plaindatetime.prototype.with

瀏覽器相容性

另見