Moment.js how to get week of month? (google calendar style)

后端 未结 12 837
挽巷
挽巷 2020-12-03 13:56

I am using Moment.js and it is great. The problem I have now is that I can\'t figure out how to get the week of the month a certain date is. I can only find \"week of year\"

12条回答
  •  旧时难觅i
    2020-12-03 14:49

    There is a problem with @Daniel Earwicker answer. I was using his function in my application and the while loop was infinite because of the following situation:

    I was trying to figure out which week of december (2016) was the day 31. the first day of december was day 336 of the year. The last day of december was day 366 of the year.

    Problem here: When it was day 366 (31 of december, last day of the year) the code added another day to this date. But with another day added it would be day 1 of january of 2017. Therefore the loop never ended.

     while (m.dayOfYear() <= yearDay) { 
    
        if (m.day() == weekDay) {
            count++; 
        }
        m.add('days', 1); 
    }
    

    I added the following lines to the code so the problem would be fixed:

    function countWeekdayOccurrencesInMonth(date) {
    
      var m = moment(date),
            weekDay = m.day(),
            yearDay = m.dayOfYear(),
            year = m.year(),
            count = 0;
    
     m.startOf('month');
    
     while (m.dayOfYear() <= yearDay && m.year() == year) {
        if (m.day() == weekDay) {
            count++;
        }
        m.add('days', 1);
     }
    
     return count;
    }
    

    It verifies if it is still in the same year of the date being veryfied

提交回复
热议问题