Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
Obtenga semanas en un mes como matriz con el nombre del día y la fecha

Tengo un código que devuelve la fecha de inicio y finalización de las semanas en un mes, pero necesito que devuelva la semana completa con fecha, día, mes

mes comienza de 0-11

 function getFullWeeksStartAndEndInMonth (month, year) { let weeks = [], firstDate = new Date(year, month, 1), lastDate = new Date(year, month + 1, 0), numDays = lastDate.getDate() let start = 1 let end if (firstDate.getDay() === 1) { end = 7 } else if (firstDate.getDay() === 0) { let preMonthEndDay = new Date(year, month, 0) start = preMonthEndDay.getDate() - 6 + 1 end = 1 } else { let preMonthEndDay = new Date(year, month, 0) start = preMonthEndDay.getDate() + 1 - firstDate.getDay() + 1 end = 7 - firstDate.getDay() + 1 weeks.push({ start: start, end: end }) start = end + 1 end = end + 7 } while (start <= numDays) { weeks.push({ start: start, end: end }); start = end + 1; end = end + 7; end = start === 1 && end === 8 ? 1 : end; if (end > numDays && start <= numDays) { end = end - numDays weeks.push({ start: start, end: end }) break } } return weeks }

Cómo obtener la fecha de la semana completa + el día + el mes, no solo la fecha de inicio y finalización como esta

 0: {date:30,month:"May",day:"Monday"},{date:31,month:"May",day:"Tuesday"},{date:1,month:"June",day:"Wednesday"},...
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Aquí tienes

Si necesita que le explique algo, hágamelo saber, es solo un mapa simple que genera siete objetos para la semana con la información requerida

por el momento, es una matriz anidada: cada elemento de la matriz externa es una matriz durante una semana

si desea aplanarlo, descomente el .flat(Infinity)

 function getFullWeeksStartAndEndInMonth (month, year) { let weeks = [], firstDate = new Date(year, month, 1), lastDate = new Date(year, month + 1, 0), numDays = lastDate.getDate() let start = 1 let end if (firstDate.getDay() === 1) { end = 7 } else if (firstDate.getDay() === 0) { let preMonthEndDay = new Date(year, month, 0) start = preMonthEndDay.getDate() - 6 + 1 end = 1 } else { let preMonthEndDay = new Date(year, month, 0) start = preMonthEndDay.getDate() + 1 - firstDate.getDay() + 1 end = 7 - firstDate.getDay() + 1 weeks.push({ start: start, end: end }) start = end + 1 end = end + 7 } while (start <= numDays) { weeks.push({ start: start, end: end }); start = end + 1; end = end + 7; end = start === 1 && end === 8 ? 1 : end; if (end > numDays && start <= numDays) { end = end - numDays weeks.push({ start: start, end: end }) break } } // *** the magic starts here return weeks.map(({start, end}, index) => { const sub = +(start > end && index === 0); return Array.from({length: 7}, (_, index) => { const date = new Date(year, month - sub, start + index); return { date: date.getDate(), month: date.toLocaleString('en', {month: 'long'}), day: date.toLocaleString('en', {weekday: 'long'}), }; }); })//.flat(Infinity); } console.log(getFullWeeksStartAndEndInMonth(6, 2022))

about 4 years ago · Juan Pablo Isaza Relatório

0

El ejemplo de salida en OP:

 0: {date: 30, month: "May", day: "Monday"}, {date: 31, month: "May", day: "Tuesday"}, {date: 1, month: "June", day: "Wednesday"},...

El 0: implica que todo a la derecha es el primer elemento de una matriz. Si es así, necesita corchetes [] , o es una cadena que necesita comillas "". En el OP, el resultado parece una matriz con otra matriz que tiene objetos. La matriz externa no tiene sentido. El ejemplo proporcionado devuelve una matriz de objetos, que es una de las estructuras de datos más utilizadas:

 [ {date: 26, month: "May", day: "Thursday"}, {date: 27, month: "May", day: "Friday"}, {date: 28, month: "May", day: "Saturday"}, {date: 29, month: "May", day: "Sunday"},... ]

Los detalles se comentan en el ejemplo.

 /** * @desc Given a start string date and an end string date, return * each day as an object consisting of {date, month, weekday} * in an array * @param {string<date>} from - A string in this format yyyy-mm-dd * @param {string<date>} to - See previous * @return {array<object>} An array of objects with the following: * {date: {number}, month: {string}, day: {string}} */ function dateRange(from, to) { // Convert the parameters into Date objects const start = new Date(from) const end = new Date(to); // Define array to return let range = []; /* While the start date is less than or equal to the end date... ...get a new date object setting it's date number ahead by 1... ...next get the new date... ...then the long version of the month... ...and then the long version of the weekday... ...create an object with those values matched to these keys: date, month, day... ...add the object to the range array */ while(start <= end) { const next = new Date(start.setDate(start.getDate()+1)); const date = next.getDate(); const month = next.toLocaleString('default', {month: 'long'}); const day = next.toLocaleString('default', {weekday: 'long'}); const dayObj = Object.assign({}, {date: date, month: month, day: day}); range.push(dayObj); } // After the while loop, return the range array return range; } console.log(dateRange('2022-05-26', '2022-06-12'));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda