Get week of the month

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

    function getWeekOfMonth(date) {
      const startWeekDayIndex = 1; // 1 MonthDay 0 Sundays
      const firstDate = new Date(date.getFullYear(), date.getMonth(), 1);
      const firstDay = firstDate.getDay();
    
      let weekNumber = Math.ceil((date.getDate() + firstDay) / 7);
      if (startWeekDayIndex === 1) {
        if (date.getDay() === 0 && date.getDate() > 1) {
          weekNumber -= 1;
        }
    
        if (firstDate.getDate() === 1 && firstDay === 0 && date.getDate() > 1) {
          weekNumber += 1;
        }
      }
      return weekNumber;
    }
    

    I hope this works Tested until 2025

提交回复
热议问题