How to get list of days in a month with Moment.js

后端 未结 11 587
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 07:17

Using Moment.js I would like to get all days in a month of specific year in an array. For example:

January-2014:
[
\"01-wed\",
\"02-thr\",
\"03-fri\",
\"04-s         


        
11条回答
  •  囚心锁ツ
    2020-12-14 08:00

    Below are two nice functional approaches with no external dependency other than Moment:

    const currentMonthDates = new Array(moment().daysInMonth()).fill(null).map((x, i) => moment().startOf('month').add(i, 'days'));
    const currentMonthDates = Array.from({length: moment().daysInMonth()}, (x, i) => moment().startOf('month').add(i, 'days'));
    

    This returns an array of Moment objects, you can then run whatever format method on it that you wish.

    For further reading Creating and filling Arrays of arbitrary lengths in JavaScript, also note that in the first example you have to fill the array with null before mapping over it, as it is still classed as empty before doing so and therefore the map function would not run.

提交回复
热议问题