Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

513
Vistas
How to make a for loop to gather every day of a week that is between months?

So, i need to gather all days the current week, from Sunday to Saturday, i started making a code that takes the actual date and make a for loop to push each day into a array, the problem is that on weeks like this one (that begins in one month and finish in another) the code wont work.

Here is the code:

const createWeek = async() => {
  const d = new Date();
  let month = d.getMonth() + 1;
  let year = d.getFullYear();
  const inicialDate = d.getDate() - d.getDay();
  const lastDate = inicialDate + 6;
  console.log(d, 'current date')

   let firstDay = new Date(d.setDate(inicialDate));
   let lastDay = new Date(d.setDate(lastDate))


   let week = []
   for (let i = firstDay.getDate(); i <= lastDay.getDate(); i++) {
     week.push(`${i.toLocaleString().length <= 1 ? "0" + i : i}${month.toLocaleString().length <= 1 ? "0" + month : month}${year}`);
   }

   return week;
}

So i know that the problem is because in my for loop the first day of the week is bigger than the final day of the week, but i dont know how to deal with that. I want to know what is the best aproach to this.

Thanks for your help.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I'd suggest using Date.setDate() to adjust each day, this will adjust the month correctly as well.

We start by getting the weekStart day, by subtracting the result of currentDay.getDay() from currentDate.getDate() and using this as the input to setDate().

We can then use Array.from() to generate our list of seven days.

I'd suggest first creating an array of seven dates, then creating a custom formatting function, e.g. formatDate() for this purpose. This allows us to separate the logic of creating and displaying the dates.

function createWeek(currentDay = new Date()) {
    const weekStart = new Date(currentDay);
    weekStart.setDate(currentDay.getDate() - currentDay.getDay());
    return Array.from( { length: 7 }, (v,k) => { 
        const dt = new Date(weekStart);
        dt.setDate(weekStart.getDate() + k);
        return dt;
    })
}

function formatDate(date) {
    return [date.getDate(), date.getMonth() + 1, date.getFullYear()]
     .map(n => (n + '').padStart(2, '0'))
     .join('');
}

const weekDates = createWeek();
console.log('Formatted dates:')
for(let date of weekDates) {
    console.log(formatDate(date));
}
.as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda