Temporal.PlainDate.prototype.daysInMonth

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

daysInMonth 访问器属性,属于 Temporal.PlainDate 实例,返回一个正整数,表示该日期所在月份的天数。它取决于日历

请注意,月份的天数并不总是等于月份最后一天的day,在极少数情况下,月份可能会跳过一些天。

daysInMonth 的设置器为 undefined。你不能直接更改此属性。

示例

使用 daysInMonth

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

const date2 = Temporal.PlainDate.from("2021-02-01");
console.log(date2.daysInMonth); // 28; 2021 is not a leap year

const date3 = Temporal.PlainDate.from("2020-02-01");
console.log(date3.daysInMonth); // 29; 2020 is a leap year

const date4 = Temporal.PlainDate.from("2021-04-01[u-ca=chinese]");
console.log(date4.month); // 2
console.log(date4.daysInMonth); // 30; the Chinese 2nd month has 30 days

切换到月份的倒数第二天

您可以使用 daysInMonth 来切换到月份的倒数第二天

js
const date = Temporal.PlainDate.from("2021-07-01");
const secondLastDay = date.with({ day: date.daysInMonth - 1 });
console.log(secondLastDay.toString()); // 2021-07-30

但这并非完全安全,因为 daysInMonth 并不保证与日期索引有任何关联。以下是获取月份倒数第二天的更安全方法

js
const date = Temporal.PlainDate.from("2021-07-01");
const secondLastDay = date
  .with({ day: Number.MAX_SAFE_INTEGER })
  .subtract({ days: 1 });
console.log(secondLastDay.toString()); // 2021-07-30

规范

规范
Temporal
# sec-get-temporal.plaindate.prototype.daysinmonth

浏览器兼容性

另见