Obtenez des semaines en mois via Javascript

Dans Javascript, comment puis-je obtenir le nombre de semaines dans un mois? Je ne peux pas trouver de code pour cela n'importe où.

J'ai besoin de cela pour savoir combien de lignes j'ai besoin pour un mois donné.

Pour être plus précis, j'aimerais le nombre de semaines qui ont au moins un jour de la semaine (une semaine étant définie comme commençant le dimanche et se terminant samedi).

Donc, pour quelque chose comme ça, je voudrais savoir qu'il a 5 semaines:

SMTWRFS 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 

Merci pour votre aide.

    Les semaines commencent dimanche

    Cela devrait fonctionner même lorsque février ne commence pas le dimanche.

     function weekCount(year, month_number) { // month_number is in the range 1..12 var firstOfMonth = new Date(year, month_number-1, 1); var lastOfMonth = new Date(year, month_number, 0); var used = firstOfMonth.getDay() + lastOfMonth.getDate(); return Math.ceil( used / 7); } 

    Les semaines commencent le lundi

     function weekCount(year, month_number) { // month_number is in the range 1..12 var firstOfMonth = new Date(year, month_number-1, 1); var lastOfMonth = new Date(year, month_number, 0); var used = firstOfMonth.getDay() + 6 + lastOfMonth.getDate(); return Math.ceil( used / 7); } 

    Les semaines commencent un autre jour

     function weekCount(year, month_number, startDayOfWeek) { // month_number is in the range 1..12 // 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 firstWeekDay = (firstOfMonth.getDay() - firstDayOfWeek + 7) % 7; var used = firstWeekDay + numberOfDaysInMonth; return Math.ceil( used / 7); } 

    Vous devrez le calculer.

    Vous pouvez faire quelque chose comme

     var firstDay = new Date(2010, 0, 1).getDay(); // get the weekday january starts on var numWeeks = 5 + (firstDay >= 5 ? 1 : 0); // if the months starts on friday, then it will end on sunday 

    Maintenant, nous devons simplement le générer.

     var dayThreshold = [ 5, 1, 5, 6, 5, 6, 5, 5, 6, 5, 6, 5 ]; function GetNumWeeks(month, year) { var firstDay = new Date(year, month, 1).getDay(); var baseWeeks = (month == 1 ? 4 : 5); // only February can fit in 4 weeks // TODO: account for leap years return baseWeeks + (firstday >= dayThreshold[month] ? 1 : 0); // add an extra week if the month starts beyond the threshold day. } 

    Remarque: Lorsque vous appelez, n'oubliez pas que les mois sont indexés zéro dans javascript (c'est-à-dire Janvier == 0).

     function weeksinMonth(m, y){ y= y || new Date().getFullYear(); var d= new Date(y, m, 0); return Math.floor((d.getDate()- 1)/7)+ 1; } alert(weeksinMonth(3)) 

    // la fourchette de mois pour cette méthode est de 1 (janvier) -12 (décembre)

    Personne parmi les solutions proposées ici ne fonctionne pas correctement, alors j'ai écrit ma propre variante et cela fonctionne pour tous les cas.

    Solution simple et fonctionnelle:

    
    

     /** * Returns count of weeks for year and month * * @param {Number} year - full year (2016) * @param {Number} month_number - month_number is in the range 1..12 * @returns {number} */ var weeksCount = function(year, month_number) { var firstOfMonth = new Date(year, month_number - 1, 1); var day = firstOfMonth.getDay() || 6; day = day === 1 ? 0 : day; if (day) { day-- } var diff = 7 - day; var lastOfMonth = new Date(year, month_number, 0); var lastDate = lastOfMonth.getDate(); if (lastOfMonth.getDay() === 1) { diff--; } var result = Math.ceil((lastDate - diff) / 7); return result + 1; }; 

    Vous pouvez l'essayer ici

    Le moyen le plus facile à comprendre est

     <div id="demo"></div> <script type="text/javascript"> function numberOfDays(year, month) { var d = new Date(year, month, 0); return d.getDate(); } function getMonthWeeks(year, month_number) { var $num_of_days = numberOfDays(year, month_number) , $num_of_weeks = 0 , $start_day_of_week = 0; for(i=1; i<=$num_of_days; i++) { var $day_of_week = new Date(year, month_number, i).getDay(); if($day_of_week==$start_day_of_week) { $num_of_weeks++; } } return $num_of_weeks; } var d = new Date() , m = d.getMonth() , y = d.getFullYear(); document.getElementById('demo').innerHTML = getMonthWeeks(y, m); </script> 

    Vous pouvez utiliser ma bibliothèque time.js. Voici la fonction WeekInMonth:

     // 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); }, 

    Cela pourrait être un peu obscur puisque la viande de la fonctionnalité se trouve dans la fin du mois et le premierDayInCalendarMonth, mais vous devriez au moins avoir une idée de la façon dont cela fonctionne.

    En utilisant le moment js

     function getWeeksInMonth(year, month){ var monthStart = moment().year(year).month(month).date(1); var monthEnd = moment().year(year).month(month).endOf('month'); var numDaysInMonth = moment().year(year).month(month).endOf('month').date(); //calculate weeks in given month var weeks = Math.ceil((numDaysInMonth + monthStart.day()) / 7); var weekRange = []; var weekStart = moment().year(year).month(month).date(1); var i=0; while(i<weeks){ var weekEnd = moment(weekStart); if(weekEnd.endOf('week').date() <= numDaysInMonth && weekEnd.month() == month) { weekEnd = weekEnd.endOf('week').format('LL'); }else{ weekEnd = moment(monthEnd); weekEnd = weekEnd.format('LL') } weekRange.push({ 'weekStart': weekStart.format('LL'), 'weekEnd': weekEnd }); weekStart = weekStart.weekday(7); i++; } return weekRange; } console.log(getWeeksInMonth(2016, 7)) 

    Merci à Ed Poor pour sa solution, c'est le même que le prototype Date.

     Date.prototype.countWeeksOfMonth = function() { var year = this.getFullYear(); var month_number = this.getMonth(); var firstOfMonth = new Date(year, month_number-1, 1); var lastOfMonth = new Date(year, month_number, 0); var used = firstOfMonth.getDay() + lastOfMonth.getDate(); return Math.ceil( used / 7); } 

    Vous pouvez donc l'utiliser comme

     var weeksInCurrentMonth = new Date().countWeeksOfMonth(); var weeksInDecember2012 = new Date(2012,12,1).countWeeksOfMonth(); // 6 

    C'est un code à deux lignes très simple. Et j'ai testé 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); } 

    Comment utiliser

     var totalWeeks = new Date().getWeekOfMonth(); console.log('Total Weeks in the Month are : + totalWeeks ); 
     function getWeeksInMonth(month_number, year) { console.log("year - "+year+" month - "+month_number+1); var day = 0; var firstOfMonth = new Date(year, month_number, 1); var lastOfMonth = new Date(year, parseInt(month_number)+1, 0); if (firstOfMonth.getDay() == 0) { day = 2; firstOfMonth = firstOfMonth.setDate(day); firstOfMonth = new Date(firstOfMonth); } else if (firstOfMonth.getDay() != 1) { day = 9-(firstOfMonth.getDay()); firstOfMonth = firstOfMonth.setDate(day); firstOfMonth = new Date(firstOfMonth); } var days = (lastOfMonth.getDate() - firstOfMonth.getDate())+1 return Math.ceil( days / 7); } 

    Cela a fonctionné pour moi. S'il vous plaît essayez

    Merci a tous

    Ce code vous donne le nombre exact de semaines dans un mois donné:

     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; } 

    La variable monthAdjustement ajoute ou supprime le mois que vous êtes actuellement

    Je l'utilise dans un projet de calendrier dans JS et l'équivalent dans Objective-C et ça marche bien