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

160
Visualizações
How do I get an array of all days in the week given the current date in javascript?

I have the weekday value (0-6 for Sun-Sat)...how do I get an array of days (starting on Sunday for the given week?

Here is what I'm trying to do:

A user clicks a day (ie: May 10) and it generates an array of the dates for the current week:


    function selectWeek(date) {
        selectedWeek = [];

        let d = new Date(date.key);

        console.log(d);
        console.log(date.weekday, 'weekday');

        console.log(date);
        for (let i = 0; i < date.weekday; i++) {
            console.log(i, 'pre');
            let currD = d.setDate(d.getDate() - i).toString();
            console.log(currD);
            selectedWeek.push(currD);
        }
        for (let i = date.weekday; i < 7; i++) {
            console.log(i, 'post');
            selectedWeek.push(d.setDate(d.getDate() + i).toString());
        }
        console.log(selectedWeek);
    }

I need Sunday through Saturday date objects.

I am not using a date library so prefer vanilla javascript solutions.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Create an array with 7 elements, subtract the weekday and add the index as day:

function selectWeek(date) {
  return Array(7).fill(new Date(date)).map((el, idx) =>
    new Date(el.setDate(el.getDate() - el.getDay() + idx)))
}

const date = new Date();
console.log(selectWeek(date));

I'm using

fill(new Date(date))

to create a copy and not modify the argument. You can get the days of a month with the same concept:

function selectMonth(date) {
  return Array(31).fill(new Date(date)).map((el, idx) =>
    new Date(el.setDate(1 + idx))).filter(el => el.getMonth() === date.getMonth());
}

const date = new Date();
console.log(selectMonth(date));

about 4 years ago · Juan Pablo Isaza Relatório

0

here's how I would solve this one:

function selectWeek(date) {
        let selectWeek = [];
        for (let i=0; i<7; i++) {
          let weekday = new Date(date) // clone the selected date, so we don't mutate it accidentally.
          let selectedWeekdayIndex = date.getDay() // i.e. 5 for friday
          let selectedDay = date.getDate() // 1-31, depending on the date
          weekday.setDate(selectedDay - selectedWeekdayIndex + i)
          selectWeek = [...selectWeek, weekday]
        }
        return selectWeek;
    }

Let's take today's date as an example: 18.02.22. Friday. We do 6 iterations. On first one we get the selectedWeekdayIndex, which is 5 for friday. We clone the date and re-set it's day (18) reducing it by this number: 18-5 = 13. This is the day for Sunday. Then we go on incrementing days by one to fill the rest of the week.

Of course it can be optimised and written much shorter, but I tried to show and explain the logic.

about 4 years ago · Juan Pablo Isaza Relatório

0

Did you check Date prototypes before?

I think Date.prototype.getDay() can do what you want:

function selectWeekDays(date) {
  var i,
      d = new Date(date),
      a = [];
  // console.log(d.getDay());   // Number of the day
  d.setDate(d.getDate() - d.getDay() - 1);   // Set date one day before first day of week
  for (i=0; i<7; i++) {
    d.setDate(d.getDate() + 1);   // Add one day
    a.push(d.valueOf());
  }
  return a;
}

var result = selectWeekDays('2022-01-01') // Satureday = 6

console.log(result); 
result.forEach(e => console.log(new Date(e).toString()));

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