如何在moment.js中获取当月的周数

时间:2017-04-25 06:50:56

标签: javascript ember.js momentjs

我想获得特定月份的周数 例如:2017年1月,本月的周数为[52,1,2,3,4,5] 那么如何在数组中获得上述内容呢? 感谢

3 个答案:

答案 0 :(得分:2)

 const firstDayOfMonth = moment(`${ year }-${ month }`, 'YYYY-MM-DD');
 const numOfDays = firstDayOfMonth.daysInMonth();
 let weeks = new Set();

 for(let i = 0; i < numOfDays; i++){
     const currentDay = moment(firstDayOfMonth, 'YYYY-MM-DD').add(i, 'days');

     weeks.add(currentDay.isoWeek());
 }

 return Array.from(weeks)

答案 1 :(得分:2)

更有效率:

 const firstDayOfMonth = moment(`${ year }-${ month }`, 'YYYY-MM-DD');
 let weekIndices = [];

 let currentDay = moment(firstDayOfMonth, 'YYYY-MM-DD');
 weekIndices.push(currentDay.isoWeek());

 while(currentDay.month() === firstDayOfMonth.month()) {
     currentDay.add(1, 'weeks');
     weekIndices.push(currentDay.isoWeek());
 }

return weekIndices;

答案 2 :(得分:0)

我知道我不应该,但我喜欢这个问题:) 你能改进吗?

    function showWeeks(year, month) {

      let firstWeek = moment(new Date(year,month,1)).isoWeek();
      let lastWeek = moment(new Date(year,month+1,0)).isoWeek();

      let out = [firstWeek];
      if (firstWeek === 52 || firstWeek === 53) {
        firstWeek=0;
      }

      for ( let i = firstWeek+1; i<= lastWeek; i++) {
        out.push(i);
      }

      return out;
    }

    console.log(showWeeks(2017, 0)); // [52, 1, 2, 3, 4, 5]
    console.log(showWeeks(2021, 0)); // [53, 1, 2, 3, 4]
    console.log(showWeeks(2017, 11)); // [48, 49, 50, 51, 52]
    console.log(showWeeks(1986, 9)); // [40, 41, 42, 43, 44]