Get Weeks In Month Through Javascript

后端 未结 17 1340
盖世英雄少女心
盖世英雄少女心 2020-11-30 09:03

In Javascript, how do I get the number of weeks in a month? I can\'t seem to find code for this anywhere.

I need this to be able to know how many rows I need for a g

17条回答
  •  庸人自扰
    2020-11-30 09:29

    function getWeeksInMonth(month_number, year) {
      console.log("year - "+year+" month - "+month_number+1);
    
      var day = 0;
      var firstOfMonth = new Date(year, month_number, 1);
      var lastOfMonth = new Date(year, parseInt(month_number)+1, 0);
    
      if (firstOfMonth.getDay() == 0) {
        day = 2;
        firstOfMonth = firstOfMonth.setDate(day);
        firstOfMonth = new Date(firstOfMonth);
      } else if (firstOfMonth.getDay() != 1) {
        day = 9-(firstOfMonth.getDay());
        firstOfMonth = firstOfMonth.setDate(day);
        firstOfMonth = new Date(firstOfMonth);
      }
    
      var days = (lastOfMonth.getDate() - firstOfMonth.getDate())+1
      return Math.ceil( days / 7);              
    }
    

    It worked for me. Please try

    Thanks all

提交回复
热议问题