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

510
Visualizações
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 Respostas
Responde à pergunta

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