Is there is an efficient way to get a count of days grouped by month in a date range?
For example, given a date range of 2020-01-30 to 2020-02-03 the output would be { 'January': 2, 'February': 3 }.
Is there is an efficient way to get a count of days grouped by month in a date range?
For example, given a date range of 2020-01-30 to 2020-02-03 the output would be { 'January': 2, 'February': 3 }.
I think there's no more efficient way other than calculating it.
const firstDateToPass = { year: 2020, month: 1, day: 26 };
const secondDateToPass = { year: 2020, month: 1, day: 29 };
const getCountOfDaysGroupedByMonth = (startDate, endDate) => {
const firstMonthDateTime = DateTime.fromObject(startDate);
const secondMonthDateTime = DateTime.fromObject(endDate);
if (firstMonthDateTime.month === secondMonthDateTime.month) {
// In same month
// Return difference in days
return {
[firstMonthDateTime.monthLong]: secondMonthDateTime.day - firstMonthDateTime.day
}
}
}
console.log(getCountOfDaysGroupedByMonth(firstDateToPass, secondDateToPass)) // { January: 3 }
You just need to cover the cases when it spans over multiple months, but I'll leave that figuring out to you for now?