Difference in Months between two dates in JavaScript

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

    function calcualteMonthYr(){
        var fromDate =new Date($('#txtDurationFrom2').val()); //date picker (text fields)
        var toDate = new Date($('#txtDurationTo2').val());
    
    var months=0;
            months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
            months -= fromDate.getMonth();
            months += toDate.getMonth();
                if (toDate.getDate() < fromDate.getDate()){
                    months--;
                }
        $('#txtTimePeriod2').val(months);
    }
    

提交回复
热议问题