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

任何帮助都是最好的:)


当前回答

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

把你的手

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

其他回答

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

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

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

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

任何值连同它的绝对值一起返回。

function differenceInMonths(firstDate, secondDate) {
    if (firstDate > secondDate) [firstDate, secondDate] = [secondDate, firstDate];
    let diffMonths = (secondDate.getFullYear() - firstDate.getFullYear()) * 12;
    diffMonths -= firstDate.getMonth();
    diffMonths += secondDate.getMonth();
    return diffMonths;
}
 
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;
}

我知道这真的很晚了,但还是把它贴出来,以防它能帮助到其他人。下面是我想出的一个函数,它似乎很好地计算了两个日期之间的月份差异。不可否认,这个方法比克劳德的方法要粗俗得多,但通过遍历日期对象提供了更准确的结果。它是在AS3中,但你应该能够放弃强类型,你会有JS。请随意让大家看起来更漂亮!

    function countMonths ( startDate:Date, endDate:Date ):int
    {
        var stepDate:Date = new Date;
        stepDate.time = startDate.time;
        var monthCount:int;

        while( stepDate.time <= endDate.time ) { 
            stepDate.month += 1;
            monthCount += 1;
        }           

        if ( stepDate != endDate ) { 
            monthCount -= 1;
        }

        return monthCount;
    }