Get Weeks In Month Through Javascript

后端 未结 17 1260
盖世英雄少女心
盖世英雄少女心 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:18

    You could use my time.js library. Here's the weeksInMonth function:

    // http://github.com/augustl/time.js/blob/623e44e7a64fdaa3c908debdefaac1618a1ccde4/time.js#L67
    
    weeksInMonth: function(){
      var millisecondsInThisMonth = this.clone().endOfMonth().epoch() - this.clone().firstDayInCalendarMonth().epoch();
      return Math.ceil(millisecondsInThisMonth / MILLISECONDS_IN_WEEK);
    },
    

    It might be a bit obscure since the meat of the functionality is in endOfMonth and firstDayInCalendarMonth, but you should at least be able to get some idea of how it works.

    0 讨论(0)
  • 2020-11-30 09:19

    None of the solutions here really worked for me. Here is my crack at it.

    // Example
    // weeksOfMonth(2019, 9) // October
    // Result: 5
    weeksOfMonth (year, monthIndex) {
      const d = new Date(year, monthIndex+ 1, 0)
      const adjustedDate = d.getDate() + d.getDay()
      return Math.ceil(adjustedDate / 7)
    }
    
    0 讨论(0)
  • 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;
    
    };
    
    0 讨论(0)
  • 2020-11-30 09:20

    This is very simple two line code. and i have tested 100%.

    Date.prototype.getWeekOfMonth = function () {
        var firstDay = new Date(this.setDate(1)).getDay();
        var totalDays = new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate();
        return Math.ceil((firstDay + totalDays) / 7);
    }
    

    How to use

    var totalWeeks = new Date().getWeekOfMonth();
    console.log('Total Weeks in the Month are : + totalWeeks ); 
    
    0 讨论(0)
  • 2020-11-30 09:20

    I know this is coming late, I have seen codes upon codes trying to get the number of weeks a particular month falls on, but many have not been really precise but most have been really informative and reusable, I'm not an expert programmer but I can really think and thanks to some codes by some people I was able to arrive at a conclusion.

    function convertDate(date) {//i lost the guy who owns this code lol
    var yyyy = date.getFullYear().toString();
    var mm = (date.getMonth()+1).toString();
    var dd  = date.getDate().toString();
    
    var mmChars = mm.split('');
    var ddChars = dd.split('');
    
    return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
    }
    
    //this line of code from https://stackoverflow.com/a/4028614/2540911
    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
    
    var myDate = new Date('2019-03-2');  
    //var myDate = new Date(); //or todays date
    
    var c = convertDate(myDate).split("-"); 
    let yr = c[0], mth = c[1], dy = c[2];
    
    weekCount(yr, mth, dy)
    
    //Ahh yes, this line of code is from Natim Up there, incredible work, https://stackoverflow.com/a/2485172/2540911
    function weekCount(year, month_number, startDayOfWeek) {
    // month_number is in the range 1..12
      console.log(weekNumber);
    
    // Get the first day of week week day (0: Sunday, 1: Monday, ...)
    var firstDayOfWeek = startDayOfWeek || 0;
    
    var firstOfMonth = new Date(year, month_number-1, 1);
    var lastOfMonth = new Date(year, month_number, 0);
    var numberOfDaysInMonth = lastOfMonth.getDate();
    var first = firstOfMonth.getDate();
    
    //initialize first week
    let weekNumber = 1;
    while(first-1 < numberOfDaysInMonth){    
    // add a day
    firstOfMonth = firstOfMonth.setDate(firstOfMonth.getDate() + 1);//this line of code from https://stackoverflow.com/a/9989458/2540911
    if(days[firstOfMonth.getDay()] === "Sunday"){//get new week every new sunday according the local date format
      //get newWeek
      weekNumber++;          
    }
    
      if(weekNumber === 3 && days[firstOfMonth.getDay()] === "Friday")
        alert(firstOfMonth);
    
      first++
     }
    }
    

    I needed this code to generate a schedule or event scheduler for a church on every 3rd friday of a new month, so you can modify this to suit your or just pick your specific date, not "friday and specify the week of the month and Voila!! here you go

    0 讨论(0)
  • 2020-11-30 09:24

    This piece of code give you the exact number of weeks in a given month:

    Date.prototype.getMonthWeek = function(monthAdjustement)
    {       
        var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
        var returnMessage = (Math.ceil(this.getDate()/7) + Math.floor(((7-firstDay)/7)));
        return returnMessage;
    }
    

    The monthAdjustement variable adds or substract the month that you are currently in

    I use it in a calendar project in JS and the equivalent in Objective-C and it works well

    0 讨论(0)
提交回复
热议问题