Difference in Months between two dates in JavaScript

后端 未结 26 2829
南方客
南方客 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 18:08

    It also counts the days and convert them in months.

    function monthDiff(d1, d2) {
        var months;
        months = (d2.getFullYear() - d1.getFullYear()) * 12;   //calculates months between two years
        months -= d1.getMonth() + 1; 
        months += d2.getMonth();  //calculates number of complete months between two months
        day1 = 30-d1.getDate();  
        day2 = day1 + d2.getDate();
        months += parseInt(day2/30);  //calculates no of complete months lie between two dates
        return months <= 0 ? 0 : months;
    }
    
    monthDiff(
        new Date(2017, 8, 8), // Aug 8th, 2017    (d1)
        new Date(2017, 12, 12)  // Dec 12th, 2017   (d2)
    );
    //return value will be 4 months 
    

提交回复
热议问题