我如何在JavaScript中计算出两个Date()对象的差异,而只返回差异中的月份数?

任何帮助都是最好的:)


当前回答

它还计算天数并以月为单位进行转换。

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 

其他回答

看看我用了什么:

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;
}

一种方法是编写一个使用JODA库的简单Java Web服务(REST/JSON)

http://joda-time.sourceforge.net/faq.html#datediff

计算两个日期之间的差异,并从javascript调用该服务。

这假设您的后端是Java。

下面是另一种更少循环的方法:

calculateTotalMonthsDifference = function(firstDate, secondDate) {
        var fm = firstDate.getMonth();
        var fy = firstDate.getFullYear();
        var sm = secondDate.getMonth();
        var sy = secondDate.getFullYear();
        var months = Math.abs(((fy - sy) * 12) + fm - sm);
        var firstBefore = firstDate > secondDate;
        firstDate.setFullYear(sy);
        firstDate.setMonth(sm);
        firstBefore ? firstDate < secondDate ? months-- : "" : secondDate < firstDate ? months-- : "";
        return months;
}

这是我能找到的最简单的解。这将直接返回月数。尽管,它总是给出一个绝对值。

new Date(new Date(d2) - new Date(d1)).getMonth();

对于非绝对值,您可以使用以下解决方案:

function diff_months(startDate, endDate) {
  let diff = new Date( new Date(endDate)  - new Date(startDate) ).getMonth();
  return endDate >= startDate ? diff : -diff;
}

#这是我写的一段很好的代码,用于获取天数和月份 从给定日期开始

把你的手

/** * Date a end day * Date b start day * @param DateA Date @param DateB Date * @returns Date difference */ function getDateDifference(dateA, DateB, type = 'month') { const END_DAY = new Date(dateA) const START_DAY = new Date(DateB) let calculatedDateBy let returnDateDiff if (type === 'month') { const startMonth = START_DAY.getMonth() const endMonth = END_DAY.getMonth() calculatedDateBy = startMonth - endMonth returnDateDiff = Math.abs( calculatedDateBy + 12 * (START_DAY.getFullYear() - END_DAY.getFullYear()) ) } else { calculatedDateBy = Math.abs(START_DAY - END_DAY) returnDateDiff = Math.ceil(calculatedDateBy / (1000 * 60 * 60 * 24)) } const out = document.getElementById('output') out.innerText = returnDateDiff return returnDateDiff } // Gets number of days from given dates /* getDateDifference('2022-03-31','2022-04-08','day') */ // Get number of months from given dates getDateDifference('2021-12-02','2022-04-08','month') <div id="output"> </div>