0

I have a React component where I have a date string from which I need to generate an array of dates representing the next 11 days excluding the starting date (10/12/2016). Not sure how to achieve this. That's what I've tried so far but the problem is that by simply looping adding 1 for each iteration on the day, it won't generate the correct date when the date range of 11 days spans between two months:

addDays = () => {
   const { startDate } = this.props.pageData.parcelDetails.parcelDetails;
   const date = new Date(startDate);
   let datesCollection = []

   for (var i = 1; i < 12; i++) {
     datesCollection.push(`${date.getDate() + i}/${date.getMonth() + 1}/${date.getFullYear()}`)
   }

   return datesCollection
}

The code above generates the following array:

[
   "11/12/2016",
   "12/12/2016",
   "13/12/2016",
   "14/12/2016",
   "15/12/2016",
   "16/12/2016",
   "17/12/2016",
   "18/12/2016",
   "19/11/2016",
   "20/12/2016",
   "21/12/2016"
]

How do I generate the correct array, with proper dates for each month?

Mauro74
  • 4,686
  • 15
  • 58
  • 80
  • 2
    `date.getMonth()` [uses a 0 based value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth), so January is 0, just add 1 to `date.getMonth()` or if you really want, use a library like `https://momentjs.com/docs/#/manipulating/` – George Oct 01 '18 at 12:36
  • @George Thank you, fixed that and edited the question accordingly. The problem is that by simply looping adding 1 for each iteration on the day, it wont generate the correct date when the date range of 11 days spans between two months – Mauro74 Oct 01 '18 at 12:55
  • In that case I suggest using [momentjs](https://momentjs.com/docs/#/manipulating/add/) where it'll handle that for you – George Oct 01 '18 at 13:00
  • possible replicate of https://stackoverflow.com/questions/563406/add-days-to-javascript-date – Tiisetso Tjabane Oct 01 '18 at 13:17

2 Answers2

0

You can try adding 1 day to each loop.

var dateuse = new Date();
dateuse.setDate(dateuse.getDate() + 1);

or you can try Moment.js

var today = moment();
var dateuse = moment(today).add(1, 'days');
George
  • 6,630
  • 2
  • 29
  • 36
fl3a
  • 108
  • 5
0

You can simply do that:

addDays = () => {
  const { startDate } = this.props.pageData.parcelDetails.parcelDetails;
  const date = new Date(startDate);
  let datesCollection = []

  for (var i = 1; i < 12; i++) {
    const newDate = new Date(date.getTime() + i * 1000 * 60 * 60 * 24);
    datesCollection.push(`${newDate.getDate()}/${newDate.getMonth() + 1}/${newDate.getFullYear()}`);
  }

  return datesCollection
}
jbialobr
  • 1,382
  • 1
  • 13
  • 14