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

任何帮助都是最好的:)


当前回答

如果你不考虑每月的日期,这是迄今为止最简单的解决方案

function monthDiff(dateTo, dateTo) 回来了 (12 * (dateTo.getFullYear) - dateyear .getFullYear() 的 /和 控制台(新日期(2000年,01年),新日期(2000年,02年)// 1 控制台,log(monthDiff, new Date(1999, 02), new Date(2000, 02)) // 12年 控制台.log(monthDiff,新日期(2009年,11年),新日期(2010年,0)// 1

注意,月份索引是基于0的。这意味着一月= 0,十二月= 11。

其他回答

你也可以考虑这个解决方案,这个函数返回整数或数字形式的月差

将开始日期作为第一个或最后一个参数传递是容错的。这意味着,函数仍然会返回相同的值。

const diffInMonths = (end, start) => { var timeDiff = Math.abs(end.getTime() - start.getTime()); 返回数学。round(timeDiff / (2e3 * 3600 * 365.25)); } const result = diffInMonths(new Date(2015, 3,28), new Date(2010, 1,25)); //显示月差值为整数/数字 console.log(结果);

anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));

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

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

JavaScript中两个日期的月份差异:

 start_date = new Date(year, month, day); //Create start date object by passing appropiate argument
 end_date = new Date(new Date(year, month, day)

从start_date到end_date的总月份:

 total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())

下面的逻辑将在几个月内取得差异

(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())