I am trying to create an array with number of days between two dates.
The dates can be anything but i am using the following for this example.
Start : 11/30/2018, End: 09/30/2019
Array= [30,31,29,30....31]
What i am trying to do:
Here date ranges from 30 to 30
and 30-29.
I have the following code:
const start = "11/30/2018";
const end = "09/30/2019";
const dates = [];
const mstart = moment(new Date(start));
const mend = moment(new Date(end));
for (let i = 0; mstart < mend ; i++) {
const daysInMonth = mstart.daysInMonth() + (i === 0 ? -1 : -1);
//mstart.daysInMonth() + (i === 0 ? -1 : 0) for the first case.
dates.push(daysInMonth);
mstart.add(1, 'M');
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Issue:
The date range works for other dates as long as it's not towards the end of the month.
I need the date range to go from start date to end date. Here, it calculates the date from 30 to 29 but as soon as it goes to February it takes 28th of that month and then starts the date range from there.
How do i fix this?
I would go about comparing the dates directly rather than by the number of days in the month. Also added in a check to make sure you capture your enddate correctly if its not the same day for start and end
const start = "11/30/2018";
const end = "09/30/2019";
const dates = [];
const mstart = moment(new Date(start));
const mend = moment(new Date(end));
let i = 0;
while (1 == 1) {
let nextStart = mstart.clone().add(i, 'M');
let nextEnd = mstart.clone().add(i + 1, 'M') > mend ? mend : mstart.clone().add(i + 1, 'M');
dates.push(nextEnd.diff(nextStart, 'days'));
if (nextEnd >= mend) {
break;
}
i += 1
}
console.log(dates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>