Difference in Months between two dates in JavaScript

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

    See what I use:

    function monthDiff() {
        var startdate = Date.parseExact($("#startingDate").val(), "dd/MM/yyyy");
        var enddate = Date.parseExact($("#endingDate").val(), "dd/MM/yyyy");
        var months = 0;
        while (startdate < enddate) {
            if (startdate.getMonth() === 1 && startdate.getDate() === 28) {
                months++;
                startdate.addMonths(1);
                startdate.addDays(2);
            } else {
                months++;
                startdate.addMonths(1);
            }
        }
        return months;
    }
    

提交回复
热议问题