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

JavascriptMomentjs

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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

Solution 4 - Javascript

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael JohansenView Question on Stackoverflow
Solution 1 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavascriptShonubi KoredeView Answer on Stackoverflow
Solution 3 - JavascriptRodneyOView Answer on Stackoverflow
Solution 4 - JavascriptMo.View Answer on Stackoverflow