Temporal.PlainDate.prototype.monthsInYear

可用性有限

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

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

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

對於 ISO 8601 日曆,這總是 12,但在其他日曆系統中可能會有所不同。例如,在使用閏月的日曆中,閏年會比平年多一個月。

monthsInYear 的設定器為 undefined。你不能直接更改此屬性。

示例

使用 monthsInYear

js
const date = Temporal.PlainDate.from("2021-07-01");
console.log(date.monthsInYear); // 12

const date2 = Temporal.PlainDate.from("2021-07-01[u-ca=chinese]");
console.log(date2.monthsInYear); // 12

const date3 = Temporal.PlainDate.from("2023-07-01[u-ca=chinese]");
console.log(date3.monthsInYear); // 13; 2023 is a Chinese leap year

更改為該年的倒數第二個月

您可以使用 monthsInYear 來更改為該年的倒數第二個月

js
const date = Temporal.PlainDate.from("2021-07-01");
const secondLastMonth = date.with({ month: date.monthsInYear - 1 });
console.log(secondLastMonth.toString()); // 2021-11-01

規範

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

瀏覽器相容性

另見