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

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

    Came to this post making a date picker (yeah...) - I went with a similar approach to the top answer but I think the for loop is a bit more intuitive/readable personally. This does use JS 0 based date so 5 = June, 1 = February, etc. - you can just omit the "+1" in the date for 1 based date.

    var getDaysInMonth = function(year, month) {
      var names = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
      var date = new Date(year, month + 1, 0);
      var days = date.getDate();
      var dayList = [];
      for (i = days; days > 0; days--) {      
        date.setDate(date.getDate() + 1);
        dayList.push((dayList.length + 1) + '-' + names[date.getDay()]);
      }
      return dayList;
    }
    

提交回复
热议问题