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

任何帮助都是最好的:)


当前回答

当日期和时间无关紧要的月份数

在这种情况下,我不关心完整的月份,部分月份,一个月有多长等等。我只需要知道月数。一个相关的现实案例是每个月都有一份报告,我需要知道应该有多少份报告。

例子:

1月= 1个月 一月到二月= 2个月 11月至1月= 3个月

这是一个详细的代码示例,以显示数字的走向。

让我们取2个时间戳,结果应该是4个月

2019年11月13日的时间戳:1573621200000 2020年2月20日的时间戳:1582261140000

可能与您的时区/时间略有不同。日、分和秒并不重要,可以包含在时间戳中,但在实际计算中我们将忽略它。

步骤1:将时间戳转换为JavaScript日期

let dateRangeStartConverted = new Date(1573621200000);
let dateRangeEndConverted = new Date(1582261140000);

步骤2:获取月份/年的整数值

let startingMonth = dateRangeStartConverted.getMonth();
let startingYear = dateRangeStartConverted.getFullYear();
let endingMonth = dateRangeEndConverted.getMonth();
let endingYear = dateRangeEndConverted.getFullYear();

这给了我们

开始月份:11 开始年份:2019年 结束月份:2 结束年份:2020年

步骤3:在月末加上(12 * (endYear - startYear)) + 1。

这使我们的开始月停留在11 这样月末就等于15 2 + (12 * (2020 - 2019))+ 1 = 15

第四步:减去月份

15 - 11 = 4;我们得到了4个月的结果。

29个月

2019年11月至2022年3月为29个月。如果你把这些输入到excel电子表格中,你会看到29行。

开始的月份是11 最后一个月是403 + (12 * (2022-2019))+ 1

40 minus 11 is 29

其他回答

如果你需要计算完整的月份,不管这个月是28、29、30还是31天。下面应该可以。

var months = to.getMonth() - from.getMonth() 
    + (12 * (to.getFullYear() - from.getFullYear()));

if(to.getDate() < from.getDate()){
    months--;
}
return months;

这是答案https://stackoverflow.com/a/4312956/1987208的扩展版本,但修复了从1月31日到2月1日(1天)计算1个月的情况。

这将包括以下内容;

1月1日至1月31日—> 30天—>将导致0(逻辑上,因为它不是一个完整的月) 2月1日至3月1日-> 28或29天->将导致1(逻辑上,因为它是一个完整的月) 2月15日至3月15日-> 28或29天->将导致1(逻辑上,因为一个月过去了) 1月31日至2月1日-> 1天->结果为0(明显,但在1个月后的结果中提到的答案)

有时你可能想要得到两个日期之间的月份数量,完全忽略日期部分。例如,如果你有两个日期——2013/06/21和2013/10/18——你只关心2013/06和2013/10部分,下面是场景和可能的解决方案:

var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths; 

1.如果您只想知道两个日期之间的月份数,不包括第1个月和第2个月

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;

2.如果你想包括这两个月中的任何一个

numberOfMonths = (year2 - year1) * 12 + (month2 - month1);

3.如果你想包括这两个月

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
function calcualteMonthYr(){
    var fromDate =new Date($('#txtDurationFrom2').val()); //date picker (text fields)
    var toDate = new Date($('#txtDurationTo2').val());

var months=0;
        months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
        months -= fromDate.getMonth();
        months += toDate.getMonth();
            if (toDate.getDate() < fromDate.getDate()){
                months--;
            }
    $('#txtTimePeriod2').val(months);
}

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

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

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

这假设您的后端是Java。

下面是一个函数,它精确地提供了两个日期之间的月数。 默认行为只计算整个月份,例如3个月和1天将导致3个月的差异。您可以通过将roundUpFractionalMonths参数设置为true来防止这种情况,因此3个月和1天的差异将返回为4个月。

上面公认的答案(T.J.克劳德的答案)是不准确的,它有时会返回错误的值。

例如,monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015'))返回0,这显然是错误的。正确的差值是1个月或2个月。

这是我写的函数:

function getMonthsBetween(date1,date2,roundUpFractionalMonths)
{
    //Months will be calculated between start and end dates.
    //Make sure start date is less than end date.
    //But remember if the difference should be negative.
    var startDate=date1;
    var endDate=date2;
    var inverse=false;
    if(date1>date2)
    {
        startDate=date2;
        endDate=date1;
        inverse=true;
    }

    //Calculate the differences between the start and end dates
    var yearsDifference=endDate.getFullYear()-startDate.getFullYear();
    var monthsDifference=endDate.getMonth()-startDate.getMonth();
    var daysDifference=endDate.getDate()-startDate.getDate();

    var monthCorrection=0;
    //If roundUpFractionalMonths is true, check if an extra month needs to be added from rounding up.
    //The difference is done by ceiling (round up), e.g. 3 months and 1 day will be 4 months.
    if(roundUpFractionalMonths===true && daysDifference>0)
    {
        monthCorrection=1;
    }
    //If the day difference between the 2 months is negative, the last month is not a whole month.
    else if(roundUpFractionalMonths!==true && daysDifference<0)
    {
        monthCorrection=-1;
    }

    return (inverse?-1:1)*(yearsDifference*12+monthsDifference+monthCorrection);
};