Temporal.PlainDateTime.from()

可用性有限

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

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

Temporal.PlainDateTime.from() 靜態方法從另一個 Temporal.PlainDateTime 物件、一個包含日期和時間屬性的物件或一個 RFC 9557 字串建立一個新的 Temporal.PlainDateTime 物件。

語法

js
Temporal.PlainDateTime.from(info)
Temporal.PlainDateTime.from(info, options)

引數

info

以下之一:

  • 一個 Temporal.PlainDateTime 例項,它會建立該例項的副本。
  • 一個 RFC 9557 字串,包含日期,可選的時間,以及可選的日曆。
  • 一個物件,包含由 Temporal.PlainDate.from()calendareraeraYearyearmonthmonthCodeday)或 Temporal.PlainTime.from()hourminutesecondmillisecondmicrosecondnanosecond)識別的屬性。該資訊應明確指定年份(以 yeareraeraYear 的形式)、月份(以 monthmonthCode 的形式)和日期;其他都是可選的,並將設定為其預設值。
options 可選

包含以下屬性的物件

overflow 可選

一個字串,指定當日期元件超出範圍時(使用物件 info 時)的行為。可能的值有:

"constrain"(預設)

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

"reject"

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

返回值

一個新的 Temporal.PlainDateTime 物件,表示由 info 在指定的 calendar 中指定的日期和時間。

異常

TypeError

在以下情況之一中丟擲

  • info 不是物件或字串。
  • options 不是物件或 undefined
  • 提供的屬性不足以明確確定日期。您通常需要提供 year(或 eraeraYear)、month(或 monthCode)和 day
RangeError

在以下情況之一中丟擲

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

示例

從物件建立 PlainDateTime

js
// Year + month + day + hour + minute + second
const dt = Temporal.PlainDateTime.from({
  year: 2021,
  month: 7,
  day: 1,
  hour: 12,
  minute: 34,
  second: 56,
});
console.log(dt.toString()); // "2021-07-01T12:34:56"

從字串建立 PlainDateTime

js
const dt = Temporal.PlainDateTime.from("2021-07-01T12:34:56");
console.log(dt.toLocaleString()); // "7/1/2021, 12:34:56 PM" (assuming en-US locale)

有關更多示例,特別是關於不同日曆和溢位設定的示例,請參閱 Temporal.PlainDate.from()Temporal.PlainTime.from()

規範

規範
Temporal
# sec-temporal.plaindatetime.from

瀏覽器相容性

另見