Get Weeks In Month Through Javascript

后端 未结 17 1357
盖世英雄少女心
盖世英雄少女心 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:40

    Thanks to Ed Poor for his solution, this is the same as Date prototype.

    Date.prototype.countWeeksOfMonth = function() {
      var year         = this.getFullYear();
      var month_number = this.getMonth();
      var firstOfMonth = new Date(year, month_number-1, 1);
      var lastOfMonth  = new Date(year, month_number, 0);
      var used         = firstOfMonth.getDay() + lastOfMonth.getDate();
      return Math.ceil( used / 7);
    }
    

    So you can use it like

    var weeksInCurrentMonth = new Date().countWeeksOfMonth();
    var weeksInDecember2012 = new Date(2012,12,1).countWeeksOfMonth(); // 6
    

提交回复
热议问题