Temporal.PlainDate.prototype.month

可用性有限

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

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

Temporal.PlainDate 实例的 month 访问器属性返回一个正整数,表示此日期所在年份的 1 基月份索引。该年份的第一个月是 1,最后一个月是 monthsInYear。它取决于 日历

请注意,与 Date.prototype.getMonth() 不同,索引是 1 基的。如果日历有闰月,则具有相同 monthCode 的月份对于不同的年份可能具有不同的 month 索引。

注意:请勿使用此属性来识别实际月份,包括其名称。为此目的,请使用 monthCode。仅在年份的上下文中识别月份,或用于确定其顺序时,才使用 month

month 的设置访问器是 undefined。您不能直接更改此属性。请使用 with() 方法创建一个具有所需新值的 Temporal.PlainDate 新对象。

示例

使用 month

js
const date = Temporal.PlainDate.from("2021-07-01"); // ISO 8601 calendar
console.log(date.monthCode); // "M07"
console.log(date.month); // 7

const date2 = Temporal.PlainDate.from("2021-05-01[u-ca=chinese]");
console.log(date2.monthCode); // "M03"
console.log(date2.month); // 3; it is March 20 in the Chinese calendar

const date3 = Temporal.PlainDate.from("2023-05-01[u-ca=chinese]");
console.log(date3.monthCode); // "M03"
console.log(date3.month); // 4, although it is also March (M03)!

const date4 = Temporal.PlainDate.from("2023-04-01[u-ca=chinese]");
console.log(date4.monthCode); // "M02L"
console.log(date4.month); // 3, this month is a leap month, i.e. a duplicate February

遍历一年中的所有月份

js
const year = Temporal.PlainDate.from("2021-07-14"); // An arbitrary date in the year
for (
  let month = year.with({ month: 1 });
  month.year === year.year;
  month = month.add({ months: 1 })
) {
  console.log(month.month);
}

或者,这也是一种安全的方法(与日示例不同)

js
for (let month = 1; month <= year.monthsInYear; month++) {
  const monthDate = year.with({ month });
}

更改月份

js
const date = Temporal.PlainDate.from("2021-07-01");
const newDate = date.with({ month: 2 });
console.log(newDate.toString()); // 2021-02-01

您还可以使用 add()subtract() 来从当前日期移动指定的月份数。

js
const date = Temporal.PlainDate.from("2021-07-01");
const newDate = date.add({ months: 3 });
console.log(newDate.toString()); // 2021-10-01

默认情况下,with() 将日期约束在有效值的范围内。以下两个操作都将月份设置为该年的最后一个月

js
const date = Temporal.PlainDate.from("2021-07-01");
const lastMonth = date.with({ month: date.monthsInYear }); // 2021-12-01
const lastMonth2 = date.with({ month: Number.MAX_VALUE }); // 2021-12-01

规范

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

浏览器兼容性

另见