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

浏览器兼容性

另见