3

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

1 Answers1

1

Note: Adjust your month number ambiguity. The code itself describes all.

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

d1 = new Date("2019-08-05") // YYY-MM-DD
d2 = new Date("2022-08-05")

//Start and End Years
var start_y = d1.getFullYear();
var end_y = d2.getFullYear();

//Start and End months
var start_m = d1.getMonth();
var end_m = d2.getMonth();

var m1,m2;

//Loop all years
for( var i = start_y; i<= end_y; i++){
    m2 = (i == end_y) ?  end_m : 11;
    m1 = (i == start_y) ? start_m : 0;

    let t1 = new Date(i,m1,1), t2 = new Date(i,m2,1);

    var diff = monthDiff( t1, t2);

    console.log(`${i}[${monthNames[m1]} - ${monthNames[m2]}] = ${diff}`);

}

function monthDiff(date1, date2){
    return date2.getMonth()+1 - date1.getMonth();
}
Yasin
  • 124
  • 2
  • 11