Get week of the month

前端 未结 14 1789
野趣味
野趣味 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:29

    This is a few years on, but I've needed to use this functionality recently and, for certain dates in years 2016/2020 (such as January 31st), none of the code here works.

    It's not the most efficient by any means, but hopefully this helps someone out as it's the only thing I could get working for those years along with every other year.

    Date.prototype.getWeekOfMonth = function () {
        var dayOfMonth = this.getDay();
        var month = this.getMonth();
        var year = this.getFullYear();
        var checkDate = new Date(year, month, this.getDate());
        var checkDateTime = checkDate.getTime();
        var currentWeek = 0;
    
        for (var i = 1; i < 32; i++) {
            var loopDate = new Date(year, month, i);
    
            if (loopDate.getDay() == dayOfMonth) {
                currentWeek++;
            }
    
            if (loopDate.getTime() == checkDateTime) {
                return currentWeek;
            }
        }
    };
    

提交回复
热议问题