Difference in Months between two dates in JavaScript

后端 未结 26 2916
南方客
南方客 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

    Any value is returned along with its absolute value.

    function differenceInMonths(firstDate, secondDate) {
        if (firstDate > secondDate) [firstDate, secondDate] = [secondDate, firstDate];
        let diffMonths = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
        diffMonths -= firstDate.getMonth();
        diffMonths += secondDate.getMonth();
        return diffMonths;
    }
     
    

提交回复
热议问题