Trying to fill an array with today's days up to thirty days from now

3

Hello everyone, I'm trying to fill an array with days from the current day until 30 days from now.

Here's a problem: if today is day 8, in 30 days it will be 38, but I want the count to go back to 1 from the maximum day of each month. To work around this, I'm trying to use the following logic:

//busca o dia de hoje e preenche o array com os dias de hoje + 30 dias
     var today = new Date();
     var dd = today.getDate();
     var somaTrinta = dd + 30;
     //vetor que possui o máximo de dias por cada mês
     var diasPorMes = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
     var mm = today.getMonth();
     var maximoDias = diasPorMes[mm];
     var i;

     for(i = dd; i < somaTrinta; i++) {
       if (i > maximoDias) {
         i = 1;
       }
       horizontal.push(i);       
     }

However, after inserting the if, the page no longer loads. I do not know what my mistake is, can someone help me? Thanks

    
asked by anonymous 08.08.2017 / 14:28

3 answers

3

Using only the Date instance of javascript is enough to get you the result you want.

var hoje = new Date(); // Crio uma data
hoje.setMonth(hoje.getMonth() +1); // aplico mais um mês

var dias = [];
//percorro os dias até chegar a dia do mês seguinte
for (var dia = new Date(); dia <= hoje; dia.setDate(dia.getDate() + 1)) {
    dias.push(dia.getDate()); //salvo em um array
}
console.log(dias);
    
08.08.2017 / 15:22
4

You can use setDate() to go changing a date object and then know the day with getDate() .

var dias = 30;
var hoje = new Date();
var primeiroDia = hoje.getDate();
var array = [];
for (var i = 0; i < dias; i++) {
  hoje.setDate(primeiroDia + i)
  array.push(hoje.getDate());
}
console.log(array);

Another way, following the same logic:

var data = new Date();
var hoje = data.getDate();
var array = [...new Array(30)].map(
  (_, i) => (data.setDate(hoje + i), data.getDate())
);
console.log(array);
    
08.08.2017 / 14:44
1

Another method to achieve this is to pick up year, month and day today, and make a loop by incrementing only the day. When you spend a day with date above the month, for example January 32, the Date constructor automatically changes:

//busca o dia de hoje e preenche o array com os dias de hoje + 30 dias
var hoje = new Date();
var ano = hoje.getFullYear();
var mes = hoje.getMonth();
var dia = hoje.getDate();
var dias = []; // array de dias
for(var i = dia; i <= dia + 30; i++) {
  dias.push(new Date(ano, mes, i));
}

See it working here: link

    
08.08.2017 / 15:00