Get week of the month

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

    After reading all the answers I figured out a way that use less CPU than the others and work for every day of every month of every year. Here is my code:

    function getWeekInMonth(year, month, day){
    
        let weekNum = 1; // we start at week 1
    
        let weekDay = new Date(year, month - 1, 1).getDay(); // we get the weekDay of day 1
        weekDay = weekDay === 0 ? 6 : weekDay-1; // we recalculate the weekDay (Mon:0, Tue:1, Wed:2, Thu:3, Fri:4, Sat:5, Sun:6)
    
        let monday = 1+(7-weekDay); // we get the first monday of the month
    
        while(monday <= day) { //we calculate in wich week is our day
            weekNum++;
            monday += 7;
        }
    
        return weekNum; //we return it
    }
    

    I hope this can help.

提交回复
热议问题