This might be a duplicate with Difference in Months between two dates in JavaScript but I need to calculate the number of months PER YEAR if the inputs have multiple years.
For example:
Start Date: 2019-05-08
End Date: 2022-05-08
So that would be 3 Years but 4 Outputs in total. I need to get Number of Months per year.
startDate = "2019-08-05" // YYY-MM-DD
payOffDate = "2022-08-05"
function monthDiff(date1, date2){
months = (date2.getFullYear() - date1.getFullYear()) * 12;
months -= date1.getMonth() + 1;
months += date2.getMonth();
return months <= 0 ? 0 : months;
}
monthDiff(
new Date(startDate),
new Date(payOffDate)
); // 35 Months
In this case, it would output 35 Months by the given two inputs (startDate, payOffDate) but I wish to output them separately per year with only those two date range (not manually inputting August 2019 - Dec 2019, Jan 2022 - Aug 2022, etc)
2019 [August - December] = 4 Months
2020 [January - December] = 12 Months
2021 [January - December] = 12 Months
2022 [January - August] = 7 Months