Get week of the month

前端 未结 14 1763
野趣味
野趣味 2020-11-30 08:55

How can i get the week number of month using javascript / jquery?

For ex.:

First Week: 5th July, 2010. / Week Number = First monday

14条回答
  •  时光取名叫无心
    2020-11-30 09:27

    Having struggle with this topic too - thanks to Olson.dev! I've shortened his function a little bit, if somebody is interessted:

    // returns week of the month starting with 0
    Date.prototype.getWeekOfMonth = function() {
      var firstWeekday = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
      var offsetDate = this.getDate() + firstWeekday - 1;
      return Math.floor(offsetDate / 7);
    }
    

    update: if you need a localized version - you have to tweak the firstWeekday variable

    // german version - week starts with monday
    Date.prototype.getWeekOfMonth = function() {
      var firstWeekday = new Date(this.getFullYear(), this.getMonth(), 1).getDay() - 1;
      if (firstWeekday < 0) firstWeekday = 6;
      var offsetDate = this.getDate() + firstWeekday - 1;
      return Math.floor(offsetDate / 7);
    }
    

提交回复
热议问题