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

任何帮助都是最好的:)


当前回答

有两种方法,数学的和快速的,但受制于日历的变幻莫测,或者迭代的和缓慢的,但处理所有奇怪的(或者至少委托处理它们到一个经过良好测试的库)。

If you iterate through the calendar, incrementing the start date by one month & seeing if we pass the end date. This delegates anomaly-handling to the built-in Date() classes, but could be slow IF you're doing this for a large number of dates. James' answer takes this approach. As much as I dislike the idea, I think this is the "safest" approach, and if you're only doing one calculation, the performance difference really is negligible. We tend to try to over-optimize tasks which will only be performed once.

现在,如果您在数据集中计算这个函数,您可能不希望在每一行上运行该函数(或者上帝禁止,每条记录多次)。在这种情况下,您几乎可以使用这里的任何其他答案,除了接受的答案,这是错误的(new Date()和new Date()之间的差异是-1)?

下面是我尝试的一种数学而快速的方法,它解释了不同的月份长度和闰年。你真的应该只使用这样的函数,如果你将应用它到一个数据集(做这个计算一遍又一遍)。如果只需要执行一次,可以使用上面James的迭代方法,因为您正在将所有(许多)异常的处理委托给Date()对象。

function diffInMonths(from, to){
    var months = to.getMonth() - from.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));

    if(to.getDate() < from.getDate()){
        var newFrom = new Date(to.getFullYear(),to.getMonth(),from.getDate());
        if (to < newFrom  && to.getMonth() == newFrom.getMonth() && to.getYear() %4 != 0){
            months--;
        }
    }

    return months;
}

其他回答

计算两个日期之间的差,包括月的分数(天)。


var difference = (date2.getDate() - date1.getDate()) / 30 +
    date2.getMonth() - date1.getMonth() +
    (12 * (date2.getFullYear() - date1.getFullYear()));

例如: 日期:24/09/2015(2015年9月24日) 日期2:09/11/2015(2015年11月9日) 差异:2.5个月

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

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

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

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

这假设您的后端是Java。

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

把你的手

/** * 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>

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

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