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

后端 未结 11 636
佛祖请我去吃肉
佛祖请我去吃肉 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 07:50

    I think that using the method moment(month).daysInMonth() to get the number of days in a month together with Array.from() to generate the array is the cleaner and performative way.

    const getDaysByMonth = (month) => {
      const daysInMonth = moment(month).daysInMonth();
      return Array.from({length: daysInMonth}, (v, k) => k + 1)
    };
    
    let month = '2019-02';
    console.log(`February => ${getDaysByMonth(month)}`);
    
    month = '2019-06';
    console.log(`June => ${getDaysByMonth(month)}`);
    
    month = '2019-07';
    console.log(`July => ${getDaysByMonth(month)}`);

提交回复
热议问题