Reputation: 5116
How would one use moment.js to get the number of days in the current month? Preferably without temporary variables.
Upvotes: 91
Views: 96904
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
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
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
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