Difference in Months between two dates in JavaScript

后端 未结 26 2910
南方客
南方客 2020-11-22 17:06

How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?

Any help would be great :)

26条回答
  •  清歌不尽
    2020-11-22 17:59

    Here you go other approach with less looping:

    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;
    }
    

提交回复
热议问题