I am trying to get the following output:
Here is my code:
const start = "12/7/2018";
const end = "10/6/2019";
var startLease = moment(start, "MM/DD/YYYY");
var endLease = moment(end, "MM/DD/YYYY");
var array = [];
var i = 0;
var nextEnd;
while (1 == 1) {
var nextStart = nextEnd ? (nextEnd.date() > 28 ? nextEnd : nextEnd) : nextEnd || startLease.clone().add(i, 'M');
nextEnd = startLease.clone().add(i + 1, 'M') > endLease ? endLease : startLease.clone().add(i + 1, 'M');
if (nextEnd.date() > 28) {
nextEnd.subtract(1, 'days')
} else {}
array.push(nextEnd.diff(nextStart, 'days'));
if (nextEnd >= endLease) {
break;
} else {}
i += 1
}
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Issue:
Instead of going from 7th-6th
, it goes from 7th-7th
of every month. I tried .subtract(1, 'days') but that doesn't output the correct values. However, this works for end of the month.
Any help is appreciated. Thank you.
I added some logging to your loop and cut it off after one iteration.
Only the first month is wrong for your example, so the issue is your expectation that if you add 1 month to December 7, 2018, you'll get January 6, 2019 (you'll actually get January 7, 2019).
I'm not sure what the condition that leads to subtracting a day is supposed to do. nextEnd.date() will resolve to the day of the month, which is always less than 28 for your example.
const start = "12/7/2018";
const end = "10/6/2019";
var startLease = moment(start, "MM/DD/YYYY");
var endLease = moment(end, "MM/DD/YYYY");
var array = [];
var i = 0;
var nextEnd;
while (1 == 1) {
var nextStart = nextEnd ? (nextEnd.date() > 28 ? nextEnd : nextEnd) : nextEnd || startLease.clone().add(i, 'M');
console.log(nextStart);
nextEnd = startLease.clone().add(i + 1, 'M') > endLease ? endLease : startLease.clone().add(i + 1, 'M');
console.log(nextEnd);
if (nextEnd.date() > 28) {
nextEnd.subtract(1, 'days')
} else {}
array.push(nextEnd.diff(nextStart, 'days'));
if (nextEnd >= endLease) {
break;
} else {}
i += 1;
break;
}
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>