Temporal.PlainDate.prototype.month

可用性有限

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

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

Temporal.PlainDate 例項的 month 訪問器屬性返回一個正整數,表示此日期所在年份的 1 基月份索引。該年份的第一個月是 1,最後一個月是 monthsInYear。它取決於 日曆

請注意,與 Date.prototype.getMonth() 不同,索引是 1 基的。如果日曆有閏月,則具有相同 monthCode 的月份對於不同的年份可能具有不同的 month 索引。

注意:請勿使用此屬性來識別實際月份,包括其名稱。為此目的,請使用 monthCode。僅在年份的上下文中識別月份,或用於確定其順序時,才使用 month

month 的設定訪問器是 undefined。您不能直接更改此屬性。請使用 with() 方法建立一個具有所需新值的 Temporal.PlainDate 新物件。

示例

使用 month

js
const date = Temporal.PlainDate.from("2021-07-01"); // ISO 8601 calendar
console.log(date.monthCode); // "M07"
console.log(date.month); // 7

const date2 = Temporal.PlainDate.from("2021-05-01[u-ca=chinese]");
console.log(date2.monthCode); // "M03"
console.log(date2.month); // 3; it is March 20 in the Chinese calendar

const date3 = Temporal.PlainDate.from("2023-05-01[u-ca=chinese]");
console.log(date3.monthCode); // "M03"
console.log(date3.month); // 4, although it is also March (M03)!

const date4 = Temporal.PlainDate.from("2023-04-01[u-ca=chinese]");
console.log(date4.monthCode); // "M02L"
console.log(date4.month); // 3, this month is a leap month, i.e. a duplicate February

遍歷一年中的所有月份

js
const year = Temporal.PlainDate.from("2021-07-14"); // An arbitrary date in the year
for (
  let month = year.with({ month: 1 });
  month.year === year.year;
  month = month.add({ months: 1 })
) {
  console.log(month.month);
}

或者,這也是一種安全的方法(與日示例不同)

js
for (let month = 1; month <= year.monthsInYear; month++) {
  const monthDate = year.with({ month });
}

更改月份

js
const date = Temporal.PlainDate.from("2021-07-01");
const newDate = date.with({ month: 2 });
console.log(newDate.toString()); // 2021-02-01

您還可以使用 add()subtract() 來從當前日期移動指定的月份數。

js
const date = Temporal.PlainDate.from("2021-07-01");
const newDate = date.add({ months: 3 });
console.log(newDate.toString()); // 2021-10-01

預設情況下,with() 將日期約束在有效值的範圍內。以下兩個操作都將月份設定為該年的最後一個月

js
const date = Temporal.PlainDate.from("2021-07-01");
const lastMonth = date.with({ month: date.monthsInYear }); // 2021-12-01
const lastMonth2 = date.with({ month: Number.MAX_VALUE }); // 2021-12-01

規範

規範
Temporal
# sec-get-temporal.plaindate.prototype.month

瀏覽器相容性

另見