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

瀏覽器相容性

另見