You can pass the frommonth
and tomonth
to the function as parameters and can perform calculation of difference..
Here new Date(frommonth.substring(0,4), frommonth.substring(4), 0)
denotes,
-> frommonth.substring(0,4)
=> Getting the year from the string
-> frommonth.substring(4)
=> Getting the month from the string
-> 0
=> Setting up date as 0.
And the same has been considered for tomonth
as well..
Also Math.round(timeDiff / (2e3 * 3600 * 365.25));
is made to consider the leap year as well..
const frommonth = "201912";
const tomonth = "201810";
const diffInMonths = (end, start) => {
var timeDiff = Math.abs(end.getTime() - start.getTime());
return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}
const result = diffInMonths(new Date(frommonth.substring(0,4), frommonth.substring(4), 0), new Date(tomonth.substring(0,4), tomonth.substring(4), 0));
//Diff in months
console.log(result);