问题
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?
回答1:
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>
回答2:
You can loop through the days between startDate
and endDate
and use moment
to take the next day, then extract the day of the month with moment(date).date()...
Do this until you arrive to the end.
Update: Add snippet:
// Returns all month days.
function getDays(start, end) {
const days = [];
start = moment(new Date(start));
end = moment(new Date(end));
while (start <= end) {
days.push(moment(start).date())
start = moment(start).add(1, 'days');
}
return days;
}
// Returns the number of month days.
function getMonthDays(start, end) {
const days = [];
start = moment(new Date(start));
end = moment(new Date(end));
while (start <= end) {
days.push(moment(start).daysInMonth())
start = moment(start).add(1, 'M');
}
return days;
}
// console.log(getDays("11/30/2018", "09/30/2019"));
console.log(getMonthDays("11/30/2018", "09/30/2019"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
来源:https://stackoverflow.com/questions/53564275/array-with-number-of-days-using-moment