Retrieve date between two dates

Asked

Viewed 34 times

0

I need to make a for between two dates, entering each day of that period.

const firstDate = new Date(_visita.data);
const secondDate = new Date(_visita.dataSaida);

1 answer

2

I suggest you take advantage of builder of Date passing the value of the date that has added up to 1 day. The constructor will make the corresponding adjustment at the end of the month, thus moving to the correct day of the following month. This way you can advance in the days until you stop on the desired day.

Example (I changed the construction of your dates to simplify):

const firstDate = new Date(2018, 1, 17);
const secondDate = new Date(2018, 2, 22);
let data = firstDate;

while (data <= secondDate){
  console.log(data); //utilizar a data para fazer algo
  data = new Date(data.getFullYear(), data.getMonth(), data.getDate() + 1);
  //                      ^--ano              ^--mês          ^--dia
}

Note that last month in the constructor starts at 0, soon the month 1 is actually February.

Browser other questions tagged

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