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 |
浏览器兼容性
加载中…
另见
Temporal.PlainDate
Temporal.PlainDate.prototype.with()
Temporal.PlainDate.prototype.add()
Temporal.PlainDate.prototype.subtract()
Temporal.PlainDate.prototype.year
Temporal.PlainDate.prototype.day
Temporal.PlainDate.prototype.monthCode
Temporal.PlainDate.prototype.daysInMonth
Temporal.PlainDate.prototype.monthsInYear