Trying to fill an array with days from now until thirty days from now

Asked

Viewed 455 times

3

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

Here is a problem: if today is the 8th, in 30 days it will be 38, but I want the count to return to 1 from the maximum day of each month. To get 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 if, the page doesn’t even load anymore. I don’t know what my mistake is, can anyone help me? Thanks

3 answers

4

You can use the setDate() to change 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);

3


Using only the instancia Date of javascript is enough to get 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);
  • Thanks Dnick, really solved my problem.

1

Another method to achieve this is to take year, month and day today, and make a loop only incrementing the day. When you spend a day with date above that has the month, for example January 32, the constructor of Date 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: https://fiddle.jshell.net/kvg3ht3d/1/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.