如何使用 Moment.js 获取当前月份的天数? 最好不要使用临时变量。
Moment has a daysInMonth function:
daysInMonth
Days in Month 1.5.0+ moment().daysInMonth(); Get the number of days in the current month. moment("2012-02", "YYYY-MM").daysInMonth() // 29 moment("2012-01", "YYYY-MM").daysInMonth() // 31
Days in Month 1.5.0+
moment().daysInMonth();
Get the number of days in the current month.
moment("2012-02", "YYYY-MM").daysInMonth() // 29 moment("2012-01", "YYYY-MM").daysInMonth() // 31
You can get the days in an array
Array.from(Array(moment('2020-02').daysInMonth()).keys()) //=> [0, 1, 2, 3, 4, 5...27, 28] Array.from(Array(moment('2020-02').daysInMonth()), (_, i) => i + 1) //=> [1, 2, 3, 4, 5...28, 29]
To return days in an array you can also use
Array.from({length: moment('2020-02').daysInMonth()}, (x, i) => moment().startOf('month').add(i, 'days').format('DD')) // ["01","02","03", "04", ... "28","29"]
MomentJS can list days of the months.
const daysofThisMonth = Array.from(Array(moment().daysInMonth()), (_, i) => i + 1); console.log(daysofThisMonth);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>