Construct an Array with the date range

Asked

Viewed 702 times

2

I will receive two dates, Example: 01/10/2017, 31/10/2017. How can I create an array with every day between these dates.

Array = ["01/10/2017", "02/10/2017", "03/10/2017", ... ,"31/10/2017"]

1 answer

5


The idea here is to add the days to the date using data.setDate. As long as the initial date is less than the final, it will be added and included in the array. The two extra functions are to keep the dates in the Brazilian format.

let d1 = toDate("01/10/2017"),
    d2 = toDate("31/10/2017"),
    intervalos = [];

intervalos.push( toString(d1) );

while ( d1 < d2 ) {
  d1.setDate( d1.getDate() + 1 );
  intervalos.push( toString(d1) );
}

console.log(intervalos);

function toDate(texto) {
  let partes = texto.split('/');
  return new Date(partes[2], partes[1]-1, partes[0]);
}

function toString(date) {
  return ('0' + date.getDate()).slice(-2) + '/' +
    ('0' + (date.getMonth() + 1)).slice(-2) + '/' +
    date.getFullYear();
}

  • Exactly what I needed, I was having trouble adding a day when I changed the month, but so it worked really well, Thank you

  • You are welcome! You can mark the answer as accepted if it served you @Erickzanetti

Browser other questions tagged

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