Michael Johansen
Michael Johansen

Reputation: 5116

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.

Upvotes: 91

Views: 96904

Answers (4)

Mo.
Mo.

Reputation: 27503

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>

Upvotes: 0

RodneyO
RodneyO

Reputation: 125

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

Upvotes: 3

Shonubi Korede
Shonubi Korede

Reputation: 591

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]

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1075327

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

Upvotes: 204

Related Questions