Temporal.PlainYearMonth.from()
Temporal.PlainYearMonth.from() 靜態方法用於從另一個 Temporal.PlainYearMonth 物件、一個包含 year 和 month 屬性的物件,或一個 RFC 9557 字串建立一個新的 Temporal.PlainYearMonth 物件。
語法
Temporal.PlainYearMonth.from(info)
Temporal.PlainYearMonth.from(info, options)
引數
info-
以下之一:
Temporal.PlainYearMonth例項,它會建立一個該例項的副本。- 一個包含日期(可選)和日曆的 RFC 9557 字串。如果日曆不是
iso8601,則必須提供日期。 - 一個包含以下屬性的物件(按檢索和驗證的順序)
calendar可選-
一個字串,對應
calendarId屬性。有關常用的日曆型別列表,請參閱Intl.supportedValuesOf()。預設為"iso8601"。所有其他屬性都將在此日曆系統中解釋(與Temporal.PlainYearMonth()建構函式不同,後者在 ISO 日曆系統中解釋這些值)。 era和eraYear-
一個字串和一個整數,對應
era和eraYear屬性。僅當日歷系統有紀元(eras)時使用。era和eraYear必須同時提供。如果未提供,則必須提供year。如果同時提供了era、eraYear和year,它們必須一致。 月份-
對應
month屬性。無論overflow選項如何,都必須為正數。 monthCode-
對應
monthCode屬性。如果未提供,則必須提供month。如果同時提供了month和monthCode,它們必須一致。 年-
對應
year屬性。
options可選-
包含以下屬性的物件
overflow可選-
一個字串,指定當日期元件超出範圍時(使用物件
info時)的行為。可能的值有:"constrain"(預設)-
日期元件被限制在有效範圍內。
"reject"-
如果日期元件超出範圍,則丟擲
RangeError。
返回值
一個 Temporal.PlainYearMonth 新物件,表示 info 中指定日曆系統下的年份和月份。
每個 PlainYearMonth 內部儲存一個完整的 ISO 8601 日期,該日期在目標日曆系統中與暴露的值具有相同的年-月。當使用 toString() 字串化時,會顯示參考日期,輸出為一個 ISO 日期。參考日期是任意選擇但一致的;也就是說,每對 (year, month) 總是對映到相同的 ISO 參考日期。它不使用輸入中提供的日期。相反,參考日期總是選擇為該月份的第一個有效日期。
這種參考日期規範化確保了 equals() 可以直接比較底層 ISO 日期,而無需額外的計算。
異常
TypeError-
在以下情況之一中丟擲
info不是物件或字串。options不是物件或undefined。- 提供的屬性不足以明確確定日期。通常需要提供
year(或era和eraYear)以及month(或monthCode)。
RangeError-
在以下情況之一中丟擲
- 指定相同元件的提供的屬性不一致。
- 提供的非數字屬性無效;例如,如果
monthCode在此日曆中從未是有效的月份程式碼。 - 提供的數字屬性超出範圍,並且
options.overflow設定為"reject"。 - 該資訊不在 可表示範圍 內,該範圍是距 Unix 紀元 ±(108 + 1) 天,或大約 ±273,972.6 年。
示例
從物件建立 PlainYearMonth
// Year + month code
const ym = Temporal.PlainYearMonth.from({ year: 2021, monthCode: "M05" });
console.log(ym.toString()); // 2021-05
// Year + month
const ym2 = Temporal.PlainYearMonth.from({ year: 2021, month: 7 });
console.log(ym2.toString()); // 2021-07
// Year + month in a different calendar
const ym3 = Temporal.PlainYearMonth.from({
year: 5730,
month: 6,
calendar: "hebrew",
});
console.log(ym3.toString()); // 1970-02-07[u-ca=hebrew]
// Year + month code in a different calendar
const ym4 = Temporal.PlainYearMonth.from({
year: 5730,
monthCode: "M05L",
calendar: "hebrew",
});
console.log(ym4.toString()); // 1970-02-07[u-ca=hebrew]
控制溢位行為
預設情況下,超出範圍的值會被裁剪到有效範圍內。
const ym1 = Temporal.PlainYearMonth.from({ year: 2021, month: 13 });
console.log(ym1.toString()); // 2021-12
// 5732 is not a Hebrew leap year, so a different monthCode is chosen
const ym2 = Temporal.PlainYearMonth.from({
year: 5732,
monthCode: "M05L",
calendar: "hebrew",
});
console.log(ym2.toLocaleString("en-US", { calendar: "hebrew" })); // Adar 5732
const underlyingDate = Temporal.PlainDate.from(ym2.toString());
console.log(underlyingDate.year, underlyingDate.monthCode); // 5732 M06
你可以將此行為更改為丟擲錯誤
Temporal.PlainYearMonth.from({ year: 2021, month: 13 }, { overflow: "reject" });
// RangeError: date value "month" not in 1..12: 13
規範
| 規範 |
|---|
| Temporal # sec-temporal.plainyearmonth.from |
瀏覽器相容性
載入中…