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

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

    Alternatively you might now use moment range to achieve this :

    const month = moment('2012-02', 'YYYY-MM');
    const range = moment().range(moment(month).startOf('month'), moment(month).endOf('month'));
    const days = range.by('days');
    
    console.log([...days].map(date => date.format('DD-ffffd')));
    
    0 讨论(0)
  • 2020-12-14 08:03

    To get days in a month with moment.js i use this one :

      function daysInMonth(month) {
        var count =  moment().month(month).daysInMonth();
        var days = [];
        for (var i = 1; i < count+1; i++) {
          days.push(moment().month(month).date(i));
        }
        return days;
      }
    

    Then to call the function

    var days = daysInMonth( moment().month() );
    
    0 讨论(0)
  • 2020-12-14 08:05

    Alternative with momentjs, working for me

    function getDaysArrayByMonth() {
      var daysInMonth = moment().daysInMonth();
      var arrDays = [];
    
      while(daysInMonth) {
        var current = moment().date(daysInMonth);
        arrDays.push(current);
        daysInMonth--;
      }
    
      return arrDays;
    }
    

    And you can check

    var schedule = getDaysArrayByMonth();
    schedule.forEach(function(item) {
      console.log(item.format("DD/MM"));
    });
    
    0 讨论(0)
  • 2020-12-14 08:06

    you can do it using for loop with moment

    var daysInMonth = [];
    
     var monthDate = moment().startOf('month'); 
    
     for(let i=0;i<monthDate.daysInMonth();i++){
        let newDay=monthDate.clone().add(i,'days');
        daysInMonth.push(newDay.format('DD-ffffd')); 
    }
        
    console.log(daysInMonth)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    0 讨论(0)
  • 2020-12-14 08:07

    You could use _.times helper from lodash alongside moment like so:

        var daysInMonth = [];
    
        var monthDate = moment().startOf('month'); // change to a date in the month of interest
    
        _.times(monthDate.daysInMonth(), function (n) {
        	 daysInMonth.push(monthDate.format('DD-ffffd'));  // your format
        	 monthDate.add(1, 'day');
        });
        
        console.log(daysInMonth)
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    0 讨论(0)
提交回复
热议问题