07 DecCalculate difference in months between two dates in Javascript
Wednesday, 07 December 2011 — 13:25Here i let you some code i wrote for this task:
calculateTotalMonthsDifference = function(firstDate, secondDate) { var fm = firstDate.getMonth(); var fy = firstDate.getFullYear(); var sm = secondDate.getMonth(); var sy = secondDate.getFullYear(); var months = Math.abs(((fy - sy) * 12) + fm - sm); var firstBefore = firstDate > secondDate; firstDate.setFullYear(sy); firstDate.setMonth(sm); firstBefore ? firstDate < secondDate ? months-- : "" : secondDate < firstDate ? months-- : ""; return months; }