Temporal.PlainDateTime.prototype.with()
Temporal.PlainDateTime 例項的 with() 方法返回一個新的 Temporal.PlainDateTime 物件,該物件表示此日期-時間,其中一些欄位已替換為新值。由於所有 Temporal 物件都被設計為不可變,因此此方法實質上充當日期-時間欄位的設定器。
要替換 calendarId 屬性,請改用 withCalendar() 方法。
語法
js
with(info)
with(info, options)
引數
info-
一個物件,包含
Temporal.PlainDateTime.from()識別的至少一個屬性(calendar除外):day、era和eraYear、hour、microsecond、millisecond、minute、month、monthCode、nanosecond、second、year。未指定的屬性使用原始日期-時間的值。你只需提供month或monthCode中的一個,以及era和eraYear或year中的一個,另一個將相應更新。 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 |
瀏覽器相容性
載入中…