una semanas semana saber que obtener numero meses mes las fecha dias como actual javascript jquery date

javascript - semanas - Conseguir semana del mes



obtener las semanas de un mes javascript (14)

Creo que esto funciona. Vuelve la semana del mes, a partir de 0:

var d = new Date(); var date = d.getDate(); var day = d.getDay(); var weekOfMonth = Math.ceil((date - 1 - day) / 7);

¿Cómo puedo obtener el número de la semana del mes usando javascript / jquery?

Por ej .:

Primera semana: 5 de julio de 2010. / Número de semana = Primer lunes

Semana anterior: 12 de julio de 2010. / Número de semana = Segundo lunes

Fecha actual: 19 de julio de 2010. / Número de semana = Tercer lunes

La próxima semana: 26 de julio de 2010. / Número de semana = Último lunes


Creo que quieres usar weekOfMonth para que te dé 1-4 o 1-5 semanas del mes. Resolví el mismo problema con esto:

var dated = new Date(); var weekOfMonth = (0 | dated.getDate() / 7)+1;


Después de leer todas las respuestas, descubrí una forma en la que utilizaba menos CPU que las demás y trabajaba todos los días de cada mes de cada año. Aquí está mi código:

function getWeekInMonth(year, month, day){ let weekNum = 1; // we start at week 1 let weekDay = new Date(year, month - 1, 1).getDay(); // we get the weekDay of day 1 weekDay = weekDay === 0 ? 6 : weekDay-1; // we recalculate the weekDay (Mon:0, Tue:1, Wed:2, Thu:3, Fri:4, Sat:5, Sun:6) let monday = 1+(7-weekDay); // we get the first monday of the month while(monday <= day) { //we calculate in wich week is our day weekNum++; monday += 7; } return weekNum; //we return it }

Espero que esto pueda ayudar.


Esta es una pregunta antigua, pero las respuestas que existen son simplemente erróneas. Esta es mi solución compatible con todos los navegadores:

Date.prototype.getWeekOfMonth = function(exact) { var month = this.getMonth() , year = this.getFullYear() , firstWeekday = new Date(year, month, 1).getDay() , lastDateOfMonth = new Date(year, month + 1, 0).getDate() , offsetDate = this.getDate() + firstWeekday - 1 , index = 1 // start index at 0 or 1, your choice , weeksInMonth = index + Math.ceil((lastDateOfMonth + firstWeekday - 7) / 7) , week = index + Math.floor(offsetDate / 7) ; if (exact || week < 2 + index) return week; return week === weeksInMonth ? index + 5 : week; }; // Simple helper to parse YYYY-MM-DD as local function parseISOAsLocal(s){ var b = s.split(//D/); return new Date(b[0],b[1]-1,b[2]); } // Tests console.log(''Date Exact|expected not exact|expected''); [ [''2013-02-01'', 1, 1],[''2013-02-05'', 2, 2],[''2013-02-14'', 3, 3], [''2013-02-23'', 4, 4],[''2013-02-24'', 5, 6],[''2013-02-28'', 5, 6], [''2013-03-01'', 1, 1],[''2013-03-02'', 1, 1],[''2013-03-03'', 2, 2], [''2013-03-15'', 3, 3],[''2013-03-17'', 4, 4],[''2013-03-23'', 4, 4], [''2013-03-24'', 5, 5],[''2013-03-30'', 5, 5],[''2013-03-31'', 6, 6] ].forEach(function(test){ var d = parseISOAsLocal(test[0]) console.log(test[0] + '' '' + d.getWeekOfMonth(true) + ''|'' + test[1] + '' '' + d.getWeekOfMonth() + ''|'' + test[2]); });

No es necesario ponerlo directamente en el prototipo si no lo desea. En mi implementación, 6 significa "Último", no "Sexto". Si desea que siempre devuelva la semana real del mes, simplemente pase el valor true .

EDITAR: Se corrigió esto para manejar meses de 5 y 6 semanas. Mis "pruebas de unidad", siéntase libre de bifurcar: http://jsfiddle.net/OlsonDev/5mXF6/1/ .


Esto es algunos años después, pero he necesitado usar esta funcionalidad recientemente y, para ciertas fechas en los años 2016/2020 (como el 31 de enero), ninguno de los códigos aquí funciona.

No es el más eficiente de ninguna manera, pero espero que esto ayude a alguien, ya que es lo único en lo que puedo trabajar durante esos años junto con cada año.

Date.prototype.getWeekOfMonth = function () { var dayOfMonth = this.getDay(); var month = this.getMonth(); var year = this.getFullYear(); var checkDate = new Date(year, month, this.getDate()); var checkDateTime = checkDate.getTime(); var currentWeek = 0; for (var i = 1; i < 32; i++) { var loopDate = new Date(year, month, i); if (loopDate.getDay() == dayOfMonth) { currentWeek++; } if (loopDate.getTime() == checkDateTime) { return currentWeek; } } };


Esto no es nada apoyado de forma nativa.

Podrías rodar tu propia función para esto, trabajando desde el primer día del mes.

var currentDate = new Date(); var firstDayOfMonth = new Date( currentDate.getFullYear(), currentDate.getMonth(), 1 );

Y luego conseguir el día de la semana de esa fecha:

var firstWeekday = firstDayOfMonth.getDay();

... lo que le dará un índice basado en cero, de 0 a 6, donde 0 es el domingo.


Por favor, intente con la siguiente función. Esta está considerando la fecha de inicio de la semana como lunes y la fecha de finalización de la semana como domingo

getWeekNumber(date) { var monthStartDate =new Date(new Date().getFullYear(), new Date().getMonth(), 1); monthStartDate = new Date(monthStartDate); var day = startdate.getDay(); date = new Date(date); var date = date.getDate(); return Math.ceil((date+ day-1)/ 7); }


Simplemente pude encontrar un código más fácil para calcular el número de semanas para un mes determinado de un año ...

y == año, por ejemplo, {2012} m == es un valor de {0 - 11}

function weeks_Of_Month( y, m ) { var first = new Date(y, m,1).getDay(); var last = 32 - new Date(y, m, 32).getDate(); // logic to calculate number of weeks for the current month return Math.ceil( (first + last)/7 ); }


Teniendo problemas con este tema también, gracias a Olson.dev! He acortado un poco su función, si alguien está interesado:

// returns week of the month starting with 0 Date.prototype.getWeekOfMonth = function() { var firstWeekday = new Date(this.getFullYear(), this.getMonth(), 1).getDay(); var offsetDate = this.getDate() + firstWeekday - 1; return Math.floor(offsetDate / 7); }


function weekAndDay(date) { var days = [''Sunday'',''Monday'',''Tuesday'',''Wednesday'', ''Thursday'',''Friday'',''Saturday''], prefixes = [''First'', ''Second'', ''Third'', ''Fourth'', ''Fifth'']; return prefixes[Math.floor(date.getDate() / 7)] + '' '' + days[date.getDay()]; } console.log( weekAndDay(new Date(2010,7-1, 5)) ); // => "First Monday" console.log( weekAndDay(new Date(2010,7-1,12)) ); // => "Second Monday" console.log( weekAndDay(new Date(2010,7-1,19)) ); // => "Third Monday" console.log( weekAndDay(new Date(2010,7-1,26)) ); // => "Fourth Monday" console.log( weekAndDay(new Date()) );

Agregar la capacidad de tener Last ... puede requerir más piratería ...


function getWeekOfMonth(date) { var nth = 0; // returning variable. var timestamp = date.getTime(); // get UTC timestamp of date. var month = date.getMonth(); // get current month. var m = month; // save temp value of month. while( m == month ) { // check if m equals our date''s month. nth++; // increment our week count. // update m to reflect previous week (previous to last value of m). m = new Date(timestamp - nth * 604800000).getMonth(); } return nth; }


function getWeekOfMonth(date) { const startWeekDayIndex = 1; // 1 MonthDay 0 Sundays const firstDate = new Date(date.getFullYear(), date.getMonth(), 1); const firstDay = firstDate.getDay(); let weekNumber = Math.ceil((date.getDate() + firstDay) / 7); if (startWeekDayIndex === 1) { if (date.getDay() === 0 && date.getDate() > 1) { weekNumber -= 1; } if (firstDate.getDate() === 1 && firstDay === 0 && date.getDate() > 1) { weekNumber += 1; } } return weekNumber; }

Espero que esto funcione Probado hasta 2025.


function weekNumberForDate(date){ var janOne = new Date(date.getFullYear(),0,1); var _date = new Date(date.getFullYear(),date.getMonth(),date.getDate()); var yearDay = ((_date - janOne + 1) / 86400000);//60 * 60 * 24 * 1000 var day = janOne.getUTCDay(); if (day<4){yearDay+=day;} var week = Math.ceil(yearDay/7); return week; }

Aparentemente, la primera semana del año es la semana que contiene el primer jueves de ese año.

Sin calcular el UTCDay, la semana devuelta fue una semana antes de lo que debería haber sido. No estoy seguro de que esto no pueda mejorarse, pero parece funcionar por ahora.


week_number = 0 | new Date().getDate() / 7