Reputation: 159
var frommonth="201912";
var tomonth="201810";
From Above Two Month how i will get difference between two Month in JavaScript?
var date1 = new Date(fromdate);
var date2 = new Date(todate);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var fromYear=date1.getFullYear();
var toYear=date2.getFullYear();
var diffyear =toYear-fromYear;
Upvotes: 2
Views: 230
Reputation: 9084
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);
Upvotes: 0
Reputation: 20039
new Date()
dont parse YYYYMM
. It consider 201912
as year
So Use match()
to parse YYYYMM
var from = "201912";
var to = "201810";
function parseMonth(str) {
return str.match(/(\d{4})(\d{2})/).splice(1).map(Number)
}
var [fromY, fromM] = parseMonth(from)
var [toY, toM] = parseMonth(to)
var result = (fromY - toY) * 12 + (fromM - toM)
console.log(result, 'months')
Upvotes: 2