Using moment.js to get number of days in current month

How would one use moment.js to get the number of days in the current month? Preferably without temporary variables.


Solution 1:

Moment has a daysInMonth function:

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

Solution 2:

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]

Solution 3:

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"]