使用moment.js获取当月的天数


Answers:


170

时刻具有以下daysInMonth功能

月中的天数1.5.0+

moment().daysInMonth();

获取当月的天数。

moment("2012-02", "YYYY-MM").daysInMonth() // 29
moment("2012-01", "YYYY-MM").daysInMonth() // 31

2

你可以得到数组中的天数

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]

0

要返回数组中的天数,您也可以使用

Array.from({length: moment('2020-02').daysInMonth()}, (x, i) => moment().startOf('month').add(i, 'days').format('DD')

// ["01","02","03" ... "28","29"]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.