Temporal.PlainDate.prototype.daysInMonth
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Thuộc tính accessor daysInMonth của các instance Temporal.PlainDate trả về một số nguyên dương đại diện cho số ngày trong tháng của ngày này. Nó phụ thuộc vào lịch.
Lưu ý rằng số ngày trong tháng không phải lúc nào cũng bằng với day của ngày cuối cùng trong tháng, trong trường hợp hiếm gặp khi một tháng có thể bỏ qua một vài ngày.
Set accessor của daysInMonth là undefined. Bạn không thể thay đổi thuộc tính này trực tiếp.
Ví dụ
>Sử dụng 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 không phải năm nhuận
const date3 = Temporal.PlainDate.from("2020-02-01");
console.log(date3.daysInMonth); // 29; 2020 là năm nhuận
const date4 = Temporal.PlainDate.from("2021-04-01[u-ca=chinese]");
console.log(date4.month); // 2
console.log(date4.daysInMonth); // 30; tháng 2 của lịch Trung Quốc có 30 ngày
Thay đổi sang ngày áp chót của tháng
Bạn có thể sử dụng daysInMonth để thay đổi sang ngày áp chót của tháng:
js
const date = Temporal.PlainDate.from("2021-07-01");
const secondLastDay = date.with({ day: date.daysInMonth - 1 });
console.log(secondLastDay.toString()); // 2021-07-30
Tuy nhiên, đây không hoàn toàn an toàn, vì daysInMonth không được đảm bảo có liên quan đến chỉ mục ngày. Đây là cách an toàn hơn để lấy ngày áp chót:
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
Đặc tả
| Specification |
|---|
| Temporal> # sec-get-temporal.plaindate.prototype.daysinmonth> |
Tương thích trình duyệt
Xem thêm
Temporal.PlainDateTemporal.PlainDate.prototype.with()Temporal.PlainDate.prototype.add()Temporal.PlainDate.prototype.subtract()Temporal.PlainDate.prototype.yearTemporal.PlainDate.prototype.monthTemporal.PlainDate.prototype.dayTemporal.PlainDate.prototype.daysInWeekTemporal.PlainDate.prototype.daysInYear