2010-03-20 97 views
10

En Javascript, ¿cómo obtengo el número de semanas en un mes? Parece que no puedo encontrar el código para esto en ninguna parte.Obtener semanas en el mes mediante Javascript

Necesito esto para poder saber cuántas filas necesito para un mes determinado.

Para ser más específicos, me gustaría el número de semanas que tienen al menos un día en la semana (una semana se define como comenzando el domingo y terminando el sábado).

Así, para algo como esto, me gustaría saber que tiene 5 semanas:

S M T W R F S 

     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 

Gracias por toda la ayuda.

+1

Su pregunta le falta algunos parámetros. Las súplicas sean más específicas. Desea la cantidad de semanas completas en un mes arbitrario o desea un número real de semanas, p. 4.3, o si desea el número de semanas que tienen al menos un día en el mes? ¿Sígueme? –

Respuesta

22

Semanas comienzan el domingo

Esto se debe trabajar incluso cuando no se inicia febrero el domingo.

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

Semanas comienzan el lunes

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

Semanas comienzan otro día

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); 
} 
+2

Usó este código para un complemento de calendario jQuery. ¡Gracias por compartir! Puedes consultarlo aquí: https://github.com/joelalejandro/jquery-ja/wiki/ja.Calendar –

+1

Esto es genial. ¿Alguna posibilidad de que puedas explicar ** por qué ** esto funciona? – GotDibbs

+2

No funciona si la semana comienza el lunes;) – Titmael

3

Tendrás que calcularlo.

Usted puede hacer algo como

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 

Ahora sólo tenemos que genericize ella.

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

Nota: Al llamar, recordar que meses se indexan cero en javascript (es decir, enero == 0).

1

Puede usar my time.js library. Aquí está la función weeksInMonth:

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

que podría ser un poco oscuro ya que la carne de la funcionalidad está en EndOfMonth y firstDayInCalendarMonth, pero al menos debe ser capaz de obtener una idea de cómo funciona.

+0

¿Cómo llamarías a la función en otro script? (Todavía no soy muy bueno con Javascript) –

+1

Incluya el archivo js en su página, y haga algo como 'new Time (2008, 11) .weeksInMonth()'. –

+1

Corrígeme si me equivoco, pero ¿no dará el mismo resultado para un febrero con 28 días que comienza en domingo y un febrero estándar que comienza en cualquier otro día de la semana? Ambos tienen exactamente 4 semanas de duración, pero el primero se mostrará en 4 filas, el segundo tomará 5. –

3
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)) 

// el rango meses de este método es 1 (enero) -12 (diciembre)

0

Gracias a Ed pobre para su solución, esta es la misma que la fecha prototipo.

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

Así que se puede usar como

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

que se parece a la forma orientada a objetos para definir la función. Ideal para aquellos de nosotros con habilidades avanzadas de programación. –

+0

Sería bueno poder especificar StartWeekDay, por ejemplo, enero de 2017 comienza un domingo, por lo que son 5 semanas si la semana comienza un domingo y 6 si la semana comienza un lunes. – Natim

+0

Natim, creo que su edición de mi OP es la misma que mi re-publicación de enero de 2018. (Simplemente no sé cómo usar el operador ||, así que hice un truco de módulo). –

0

Esto es muy sencillo de dos código de línea. y lo he probado al 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); 
} 

Cómo utilizar

var totalWeeks = new Date().getWeekOfMonth(); 
console.log('Total Weeks in the Month are : + totalWeeks); 
0

Este trozo de código que da el número exacto de semanas en un mes determinado:

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 añade o restar el mes en que están actualmente en

Lo uso en un proyecto de calendario en JS y su equivalente en Ob subjetivo-C y funciona bien

3

La forma más fácil de entender es

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

Se trabajó para mí. Por favor, intente

Gracias a todos

2

usando momento 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)) 
5

Nadie de soluciones que aquí se propone no funciona correctamente, así que escribí mi propia variante y funciona para todos los casos.

solución simple y de trabajo:

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

you can try it here

0
function weekCount(year, month_number, day_start) { 

     // month_number is in the range 1..12 
     // day_start is in the range 0..6 (where Sun=0, Mon=1, ... Sat=6) 

     var firstOfMonth = new Date(year, month_number-1, 1); 
     var lastOfMonth = new Date(year, month_number, 0); 

     var dayOffset = (firstOfMonth.getDay() - day_start + 7) % 7; 
     var used = dayOffset + lastOfMonth.getDate(); 

     return Math.ceil(used/7); 
    } 
0

Esto funciona para mí,

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

"d" debería ser la fecha.

Cuestiones relacionadas