Get Weeks In Month Through Javascript

后端 未结 17 1353
盖世英雄少女心
盖世英雄少女心 2020-11-30 09:03

In Javascript, how do I get the number of weeks in a month? I can\'t seem to find code for this anywhere.

I need this to be able to know how many rows I need for a g

17条回答
  •  日久生厌
    2020-11-30 09:19

    A little rudimentary, yet should cater for original post :

    /**
     * @param {date} 2020-01-30
     * @return {int} count
     */
    this.numberOfCalendarWeekLines = date => {
    
        // get total
        let lastDayOfMonth = new Date( new Date( date ).getFullYear(), new Date( date ).getMonth() + 1, 0 );
    
        let manyDaysInMonth = lastDayOfMonth.getDate();
    
        // itterate through month - from 1st
        // count calender week lines by occurance
        // of a Saturday ( s m t w t f s )
        let countCalendarWeekLines = 0;
    
        for ( let i = 1; i <= manyDaysInMonth; i++ ) {
    
            if ( new Date( new Date( date ).setDate( i ) ).getDay() === 6 ) countCalendarWeekLines++;
    
        }
    
        // days after last occurance of Saturday 
        // leaked onto new line?
        if ( lastDayOfMonth.getDay() < 6 ) countCalendarWeekLines++;
    
        return countCalendarWeekLines;
    
    };
    

提交回复
热议问题