Your tried approach for using Date.daysInMonth(m.Year(), m.Month());
is correct, and it can help in giving you the correct number of days for a month where you have complete overlap over that month.
when you have partial overlap, at the beginning of your date range or at the end. You can still get the Date.daysInMonth()
method and get the entire months days. Then subtract the number of days that have passed. This will give you the remaining days for terminal months.
For the months in between your start and end-months. Calculation is straight forward, You need to iterate through all the months and store their days. No need to do any calculation.
I have taken 4 Jan 2020 to 14 Jan 2021 as example.
Date startDate = Date.newInstance(2020, 1, 4);
Date endDate = Date.newInstance(2021, 1, 14);
Map<String, Integer> resultMap = new Map<String, Integer>();
if(startDate > endDate) {
System.debug('start date > end date'); //incorrect call or you can even swap dates
}
//calculate the starting overlap
resultMap.put(startDate.month() + '-' + startDate.year() ,
Date.daysInMonth(startDate.year(), startDate.month()) - startDate.day()
);
//Now put the days of in between months,excluding start and end months
Date nextMonth = (startDate.addMonths(1)).toStartOfMonth();
system.debug('nextMonth : ' + nextMonth);
Date toLastMonth = (endDate.addMonths(-1)).toStartOfMonth();
system.debug('LastMonth : ' + toLastMonth);
while(nextMonth <= toLastMonth) {
resultMap.put(nextMonth.month() + '-' + nextMonth.year(), Date.daysInMonth(nextMonth.year(), nextMonth.month()));
nextMonth = nextMonth.addMonths(1); //increment by 1 month
}
//ending overlap
resultMap.put(endDate.month() + '-' + endDate.year() ,
Date.daysInMonth(endDate.year(), endDate.month()) - endDate.day()
);
for(String k : resultMap.keyset()) {
System.debug(k + ' => ' + resultMap.get(k));
}
This will print the following map, with keys being month-year, and remaining days as value.
