Get week of the month

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

    function weekNumberForDate(date){
    
        var janOne = new Date(date.getFullYear(),0,1);
        var _date = new Date(date.getFullYear(),date.getMonth(),date.getDate());
        var yearDay = ((_date - janOne + 1) / 86400000);//60 * 60 * 24 * 1000
        var day = janOne.getUTCDay();
        if (day<4){yearDay+=day;}
        var week = Math.ceil(yearDay/7);
    
       return week;
    }
    

    Apparently the first week of the year is the week that contains that year's first Thursday.

    Without calculating the UTCDay, the returned week was one week shy of what it should have been. Not confident this can't be improved, but seems to work for now.

提交回复
热议问题