Difference in Months between two dates in JavaScript

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

    getMonthDiff(d1, d2) {
        var year1 = dt1.getFullYear();
        var year2 = dt2.getFullYear();
        var month1 = dt1.getMonth();
        var month2 = dt2.getMonth();
        var day1 = dt1.getDate();
        var day2 = dt2.getDate();
        var months = month2 - month1;
        var years = year2 -year1
        days = day2 - day1;
        if (days < 0) {
            months -= 1;
        }
        if (months < 0) {
            months += 12;
        }
        return months + years*!2;
    }
    

提交回复
热议问题