大网数据广告活动
Web 标准与前端开发

Temporal.PlainDate.prototype.daysInMonth

· 52CE 我爱测

The **`daysInMonth`** accessor property of Temporal.PlainDate instances returns a positive integer representing the number of days in the month of this date. It is calendar-dependent.

The daysInMonth accessor property of Temporal.PlainDate instances returns a positive integer representing the number of days in the month of this date. It is calendar-dependent.

Note that the days in month is not always equal to the Temporal/PlainDate/day of the last day of the month, in the rare case where a month may have a few days skipped.

The set accessor of daysInMonth is undefined. You cannot change this property directly.

Examples

Using daysInMonth

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

Changing to the second last day of the month

You can use daysInMonth to change to the second last day of the month:

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

This is not totally safe, though, because daysInMonth is not guaranteed to have any connection with the day index. Here's a safer way to get the second last day:

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

Specifications

Browser compatibility

See also

  • Temporal.PlainDate
  • Temporal/PlainDate/with
  • Temporal/PlainDate/add
  • Temporal/PlainDate/subtract
  • Temporal/PlainDate/year
  • Temporal/PlainDate/month
  • Temporal/PlainDate/day
  • Temporal/PlainDate/daysInWeek
  • Temporal/PlainDate/daysInYear

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。