JavaScript中两个日期之间的月差

时间:2021-08-10 01:29:41

How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?

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

Any help would be great :)

任何帮助都是很好的。

21 个解决方案

#1


174  

The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)

“差异中的月数”的定义有很多解释。:-)

You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.

您可以从JavaScript日期对象中获取年、月和月。根据你正在寻找的信息,你可以用它们来计算两个时间点之间的月数。

For instance, off-the-cuff, this finds out how many full months lie between two dates, not counting partial months (e.g., excluding the month each date is in):

例如,即兴的,这可以发现两个日期之间有多少个完整的月份,而不包括部分月份(例如,不包括每个月的日期):

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 15: December 2008, all of 2009, and Jan & Feb 2010

monthDiff(
    new Date(2010, 0, 1),  // January 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 1: February 2010 is the only full month between them

monthDiff(
    new Date(2010, 1, 1),  // February 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 0: There are no *full* months between them

(Note that month values in JavaScript start with 0 = January.)

(注意,JavaScript中的月值以0 = 1月开始。)

Including fractional months in the above is much more complicated, because three days in a typical February is a larger fraction of that month (~10.714%) than three days in August (~9.677%), and of course even February is a moving target depending on whether it's a leap year.

将部分月份包含在上面要复杂得多,因为典型的2月份的3天(约10.714%)要比8月份的3天(约9.677%)大得多,当然,即使是2月份也是一个移动目标,这取决于它是否是闰年。

There are also some date and time libraries available for JavaScript that probably make this sort of thing easier.

JavaScript也有一些日期和时间库,这可能会使这类事情变得更容易。

#2


51  

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

#3


25  

Sometimes you may want to get just the quantity of the months between two dates totally ignoring the day part. So for instance, if you had two dates- 2013/06/21 and 2013/10/18- and you only cared about the 2013/06 and 2013/10 parts, here are the scenarios and possible solutions:

有时你可能想要得到两个日期之间的月份数量,而完全忽略了一天。例如,如果你有两个日期——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.If you want just the number of the months between the two dates excluding both month1 and month2

1。如果你只想要两个日期之间的月份数,不包括月份和月份

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

2.If you want to include either of the months

2。如果你想要包含任何一个月

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

3.If you want to include both of the months

3所示。如果你想包含这两个月

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

#4


21  

If you need to count full months, regardless of the month being 28, 29, 30 or 31 days. Below should work.

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

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

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

This is an extended version of the answer https://*.com/a/4312956/1987208 but fixes the case where it calculates 1 month for the case from 31st of January to 1st of February (1day).

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

This will cover the following;

这将包括以下内容;

  • 1st Jan to 31st Jan ---> 30days ---> will result in 0 (logical since it is not a full month)
  • 1月1日至1月31日---> 30天--->将导致0(合乎逻辑,因为不是一个完整的月)
  • 1st Feb to 1st Mar ---> 28 or 29 days ---> will result in 1 (logical since it is a full month)
  • 2月1日至3月1日---> 28或29天--->将产生1个(合乎逻辑,因为是一个月)
  • 15th Feb to 15th Mar ---> 28 or 29 days ---> will result in 1 (logical since a month passed)
  • 2月15日至3月15日---> 28或29天--->将产生1个(自一个月后合乎逻辑)
  • 31st Jan to 1st Feb ---> 1 day ---> will result in 0 (obvious but the mentioned answer in the post results in 1 month)
  • 1月31日至2月1日——> 1日——>将导致0(明显但在1个月后的结果中提到的答案)

#5


19  

Here's a function that accurately provides the number of months between 2 dates.
The default behavior only counts whole months, e.g. 3 months and 1 day will result in a difference of 3 months. You can prevent this by setting the roundUpFractionalMonths param as true, so a 3 month and 1 day difference will be returned as 4 months.

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

The accepted answer above (T.J. Crowder's answer) isn't accurate, it returns wrong values sometimes.

以上所接受的答案(T.J.克劳德的答案)不准确,有时会返回错误的值。

For example, monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015')) returns 0 which is obviously wrong. The correct difference is either 1 whole month or 2 months rounded-up.

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

Here's the function I wrote:

这是我写的函数:

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

#6


7  

Difference in Months between two dates in JavaScript:

两个日期之间的差异,在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)

total months between start_date and end_date :

start_date和end_date之间的月数:

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

#7


5  

I know this is really late, but posting it anyway just in case it helps others. Here is a function I came up with that seems to do a good job of counting differences in months between two dates. It is admittedly a great deal raunchier than Mr.Crowder's, but provides more accurate results by stepping through the date object. It is in AS3 but you should just be able to drop the strong typing and you'll have JS. Feel free to make it nicer looking anyone out there!

我知道现在已经很晚了,但还是把它贴出来,以防对别人有帮助。这是我想到的一个函数,它在计算两个约会之间几个月的差异方面做得很好。诚然,它比克劳德的更令人讨厌,但通过逐步地遍历date对象,它提供了更准确的结果。它在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;
    }

#8


5  

Consider each date in terms of months, then subtract to find the difference.

以月份为单位来考虑每个日期,然后减去以找出差异。

var past_date = new Date('11/1/2014');
var current_date = new Date();

var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());

This will get you the difference of months between the two dates, ignoring the days.

这将会使你在两个日期之间的月差,忽略天数。

#9


4  

To expand on @T.J.'s answer, if you're looking for simple months, rather than full calendar months, you could just check if d2's date is greater than or equal to than d1's. That is, if d2 is later in its month than d1 is in its month, then there is 1 more month. So you should be able to just do this:

扩大在@T.J。如果你寻找的是简单的月份,而不是完整的日历月份,你可以检查d2的日期是否大于或等于d1的日期。也就是说,如果d2的月份比d1晚些,那么还有1个月。所以你应该可以这样做:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    // edit: increment months if d2 comes later in its month than d1 in its month
    if (d2.getDate() >= d1.getDate())
        months++
    // end edit
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10

This doesn't totally account for time issues (e.g. 3 March at 4:00pm and 3 April at 3:00pm), but it's more accurate and for just a couple lines of code.

这并不能完全解释时间问题(例如3月3日下午4点和4月3日下午3点),但它更准确,只需要几行代码。

#10


4  

There are two approaches, mathematical & quick, but subject to vagaries in the calendar, or iterative & slow, but handles all the oddities (or at least delegates handling them to a well-tested library).

有两种方法,数学上的和快速的,但是会受到日历的变化,或者迭代和缓慢的影响,但是会处理所有奇怪的东西(或者至少委托处理它们到一个经过良好测试的库中)。

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.

如果你迭代日历,将开始日期增加一个月,看看我们是否通过了结束日期。这代表了对内置日期()类的异常处理,但是如果您这么做大量的日期,可能会比较慢。詹姆斯的回答采用了这种方法。尽管我不喜欢这个想法,但我认为这是“最安全”的方法,如果只做一次计算,性能差异实际上是可以忽略不计的。我们倾向于过度优化只执行一次的任务。

Now, if you're calculating this function on a dataset, you probably don't want to run that function on each row (or god forbid, multiple times per record). In that case, you can use almost any of the other answers here except the accepted answer, which is just wrong (difference between new Date() and new Date() is -1)?

现在,如果你在一个数据集中计算这个函数,你可能不希望在每一行上运行这个函数(或者上帝不允许,每个记录上运行多次)。在这种情况下,您可以使用几乎所有其他的答案,除了被接受的答案,这是错误的(新日期()和新日期()之间的区别是-1)?

Here's my stab at a mathematical-and-quick approach, which accounts for differing month lengths and leap years. You really should only use a function like this if you'll be applying this to a dataset (doing this calculation over & over). If you just need to do it once, use James' iterative approach above, as you're delegating handling all the (many) exceptions to the Date() object.

下面是我对一种数学快速方法的尝试,它解释了不同的月长和闰年。如果要对数据集应用这样的函数(进行反复的计算),您确实应该只使用这样的函数。如果您只需要做一次,请使用上面的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;
}

#11


3  

Here you go other approach with less looping:

在这里,你可以用更少的循环:

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

#12


2  

This should work fine:

这应该工作很好:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months += d2.getMonth() - d1.getMonth();
    return months;
}

#13


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

#14


1  

Calculate the difference between two dates include fraction of month (days).

计算两个日期之间的差异包括月份(天)。


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

For example:
date1: 24/09/2015 (24th Sept 2015)
date2: 09/11/2015 (9th Nov 2015)
the difference: 2.5 (months)

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

#15


1  

Following code returns full months between two dates by taking nr of days of partial months into account as well.

以下代码将在两个日期之间返回完整的月份,并将部分月份的nr计算在内。

var monthDiff = function(d1, d2) {
  if( d2 < d1 ) { 
    var dTmp = d2;
    d2 = d1;
    d1 = dTmp;
  }

  var months = (d2.getFullYear() - d1.getFullYear()) * 12;
  months -= d1.getMonth() + 1;
  months += d2.getMonth();

  if( d1.getDate() <= d2.getDate() ) months += 1;

  return months;
}

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0

monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0

#16


1  

function monthDiff(d1, d2) {
var months, d1day, d2day, d1new, d2new, diffdate,d2month,d2year,d1maxday,d2maxday;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
months = (months <= 0 ? 0 : months);
d1day = d1.getDate();
d2day = d2.getDate();
if(d1day > d2day)
{
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d1new = new Date(d2year, d2month-1, d1day,0,0,0,0);
    var timeDiff = Math.abs(d2.getTime() - d1new.getTime());
          diffdate = Math.abs(Math.ceil(timeDiff / (1000 * 3600 * 24))); 
    d1new = new Date(d2year, d2month, 1,0,0,0,0);
    d1new.setDate(d1new.getDate()-1);
    d1maxday = d1new.getDate();
    months += diffdate / d1maxday;
}
else
{
      if(!(d1.getMonth() == d2.getMonth() && d1.getFullYear() == d2.getFullYear()))
    {
        months += 1;
    }
    diffdate = d2day - d1day + 1;
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d2new = new Date(d2year, d2month + 1, 1, 0, 0, 0, 0);
    d2new.setDate(d2new.getDate()-1);
    d2maxday = d2new.getDate();
    months += diffdate / d2maxday;
}

return months;

}

}

#17


1  

below logic will fetch difference in months

下面的逻辑将在几个月内带来不同。

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

#18


0  

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

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

#19


0  

See what I use:

明白我的使用:

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

#20


0  

It also counts the days and convert them in months.

它也计算天数,并在几个月内转换。

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 

#21


-6  

One approach would be to write a simple Java Web Service (REST/JSON) that uses JODA library

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

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

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

to calculate difference between two dates and call that service from javascript.

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

This assumes your back end is in Java.

这假定您的后端是Java。

#1


174  

The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)

“差异中的月数”的定义有很多解释。:-)

You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.

您可以从JavaScript日期对象中获取年、月和月。根据你正在寻找的信息,你可以用它们来计算两个时间点之间的月数。

For instance, off-the-cuff, this finds out how many full months lie between two dates, not counting partial months (e.g., excluding the month each date is in):

例如,即兴的,这可以发现两个日期之间有多少个完整的月份,而不包括部分月份(例如,不包括每个月的日期):

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 15: December 2008, all of 2009, and Jan & Feb 2010

monthDiff(
    new Date(2010, 0, 1),  // January 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 1: February 2010 is the only full month between them

monthDiff(
    new Date(2010, 1, 1),  // February 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 0: There are no *full* months between them

(Note that month values in JavaScript start with 0 = January.)

(注意,JavaScript中的月值以0 = 1月开始。)

Including fractional months in the above is much more complicated, because three days in a typical February is a larger fraction of that month (~10.714%) than three days in August (~9.677%), and of course even February is a moving target depending on whether it's a leap year.

将部分月份包含在上面要复杂得多,因为典型的2月份的3天(约10.714%)要比8月份的3天(约9.677%)大得多,当然,即使是2月份也是一个移动目标,这取决于它是否是闰年。

There are also some date and time libraries available for JavaScript that probably make this sort of thing easier.

JavaScript也有一些日期和时间库,这可能会使这类事情变得更容易。

#2


51  

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

#3


25  

Sometimes you may want to get just the quantity of the months between two dates totally ignoring the day part. So for instance, if you had two dates- 2013/06/21 and 2013/10/18- and you only cared about the 2013/06 and 2013/10 parts, here are the scenarios and possible solutions:

有时你可能想要得到两个日期之间的月份数量,而完全忽略了一天。例如,如果你有两个日期——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.If you want just the number of the months between the two dates excluding both month1 and month2

1。如果你只想要两个日期之间的月份数,不包括月份和月份

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

2.If you want to include either of the months

2。如果你想要包含任何一个月

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

3.If you want to include both of the months

3所示。如果你想包含这两个月

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

#4


21  

If you need to count full months, regardless of the month being 28, 29, 30 or 31 days. Below should work.

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

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

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

This is an extended version of the answer https://*.com/a/4312956/1987208 but fixes the case where it calculates 1 month for the case from 31st of January to 1st of February (1day).

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

This will cover the following;

这将包括以下内容;

  • 1st Jan to 31st Jan ---> 30days ---> will result in 0 (logical since it is not a full month)
  • 1月1日至1月31日---> 30天--->将导致0(合乎逻辑,因为不是一个完整的月)
  • 1st Feb to 1st Mar ---> 28 or 29 days ---> will result in 1 (logical since it is a full month)
  • 2月1日至3月1日---> 28或29天--->将产生1个(合乎逻辑,因为是一个月)
  • 15th Feb to 15th Mar ---> 28 or 29 days ---> will result in 1 (logical since a month passed)
  • 2月15日至3月15日---> 28或29天--->将产生1个(自一个月后合乎逻辑)
  • 31st Jan to 1st Feb ---> 1 day ---> will result in 0 (obvious but the mentioned answer in the post results in 1 month)
  • 1月31日至2月1日——> 1日——>将导致0(明显但在1个月后的结果中提到的答案)

#5


19  

Here's a function that accurately provides the number of months between 2 dates.
The default behavior only counts whole months, e.g. 3 months and 1 day will result in a difference of 3 months. You can prevent this by setting the roundUpFractionalMonths param as true, so a 3 month and 1 day difference will be returned as 4 months.

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

The accepted answer above (T.J. Crowder's answer) isn't accurate, it returns wrong values sometimes.

以上所接受的答案(T.J.克劳德的答案)不准确,有时会返回错误的值。

For example, monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015')) returns 0 which is obviously wrong. The correct difference is either 1 whole month or 2 months rounded-up.

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

Here's the function I wrote:

这是我写的函数:

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

#6


7  

Difference in Months between two dates in JavaScript:

两个日期之间的差异,在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)

total months between start_date and end_date :

start_date和end_date之间的月数:

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

#7


5  

I know this is really late, but posting it anyway just in case it helps others. Here is a function I came up with that seems to do a good job of counting differences in months between two dates. It is admittedly a great deal raunchier than Mr.Crowder's, but provides more accurate results by stepping through the date object. It is in AS3 but you should just be able to drop the strong typing and you'll have JS. Feel free to make it nicer looking anyone out there!

我知道现在已经很晚了,但还是把它贴出来,以防对别人有帮助。这是我想到的一个函数,它在计算两个约会之间几个月的差异方面做得很好。诚然,它比克劳德的更令人讨厌,但通过逐步地遍历date对象,它提供了更准确的结果。它在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;
    }

#8


5  

Consider each date in terms of months, then subtract to find the difference.

以月份为单位来考虑每个日期,然后减去以找出差异。

var past_date = new Date('11/1/2014');
var current_date = new Date();

var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());

This will get you the difference of months between the two dates, ignoring the days.

这将会使你在两个日期之间的月差,忽略天数。

#9


4  

To expand on @T.J.'s answer, if you're looking for simple months, rather than full calendar months, you could just check if d2's date is greater than or equal to than d1's. That is, if d2 is later in its month than d1 is in its month, then there is 1 more month. So you should be able to just do this:

扩大在@T.J。如果你寻找的是简单的月份,而不是完整的日历月份,你可以检查d2的日期是否大于或等于d1的日期。也就是说,如果d2的月份比d1晚些,那么还有1个月。所以你应该可以这样做:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    // edit: increment months if d2 comes later in its month than d1 in its month
    if (d2.getDate() >= d1.getDate())
        months++
    // end edit
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10

This doesn't totally account for time issues (e.g. 3 March at 4:00pm and 3 April at 3:00pm), but it's more accurate and for just a couple lines of code.

这并不能完全解释时间问题(例如3月3日下午4点和4月3日下午3点),但它更准确,只需要几行代码。

#10


4  

There are two approaches, mathematical & quick, but subject to vagaries in the calendar, or iterative & slow, but handles all the oddities (or at least delegates handling them to a well-tested library).

有两种方法,数学上的和快速的,但是会受到日历的变化,或者迭代和缓慢的影响,但是会处理所有奇怪的东西(或者至少委托处理它们到一个经过良好测试的库中)。

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.

如果你迭代日历,将开始日期增加一个月,看看我们是否通过了结束日期。这代表了对内置日期()类的异常处理,但是如果您这么做大量的日期,可能会比较慢。詹姆斯的回答采用了这种方法。尽管我不喜欢这个想法,但我认为这是“最安全”的方法,如果只做一次计算,性能差异实际上是可以忽略不计的。我们倾向于过度优化只执行一次的任务。

Now, if you're calculating this function on a dataset, you probably don't want to run that function on each row (or god forbid, multiple times per record). In that case, you can use almost any of the other answers here except the accepted answer, which is just wrong (difference between new Date() and new Date() is -1)?

现在,如果你在一个数据集中计算这个函数,你可能不希望在每一行上运行这个函数(或者上帝不允许,每个记录上运行多次)。在这种情况下,您可以使用几乎所有其他的答案,除了被接受的答案,这是错误的(新日期()和新日期()之间的区别是-1)?

Here's my stab at a mathematical-and-quick approach, which accounts for differing month lengths and leap years. You really should only use a function like this if you'll be applying this to a dataset (doing this calculation over & over). If you just need to do it once, use James' iterative approach above, as you're delegating handling all the (many) exceptions to the Date() object.

下面是我对一种数学快速方法的尝试,它解释了不同的月长和闰年。如果要对数据集应用这样的函数(进行反复的计算),您确实应该只使用这样的函数。如果您只需要做一次,请使用上面的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;
}

#11


3  

Here you go other approach with less looping:

在这里,你可以用更少的循环:

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

#12


2  

This should work fine:

这应该工作很好:

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months += d2.getMonth() - d1.getMonth();
    return months;
}

#13


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

#14


1  

Calculate the difference between two dates include fraction of month (days).

计算两个日期之间的差异包括月份(天)。


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

For example:
date1: 24/09/2015 (24th Sept 2015)
date2: 09/11/2015 (9th Nov 2015)
the difference: 2.5 (months)

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

#15


1  

Following code returns full months between two dates by taking nr of days of partial months into account as well.

以下代码将在两个日期之间返回完整的月份,并将部分月份的nr计算在内。

var monthDiff = function(d1, d2) {
  if( d2 < d1 ) { 
    var dTmp = d2;
    d2 = d1;
    d1 = dTmp;
  }

  var months = (d2.getFullYear() - d1.getFullYear()) * 12;
  months -= d1.getMonth() + 1;
  months += d2.getMonth();

  if( d1.getDate() <= d2.getDate() ) months += 1;

  return months;
}

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0

monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0

#16


1  

function monthDiff(d1, d2) {
var months, d1day, d2day, d1new, d2new, diffdate,d2month,d2year,d1maxday,d2maxday;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
months = (months <= 0 ? 0 : months);
d1day = d1.getDate();
d2day = d2.getDate();
if(d1day > d2day)
{
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d1new = new Date(d2year, d2month-1, d1day,0,0,0,0);
    var timeDiff = Math.abs(d2.getTime() - d1new.getTime());
          diffdate = Math.abs(Math.ceil(timeDiff / (1000 * 3600 * 24))); 
    d1new = new Date(d2year, d2month, 1,0,0,0,0);
    d1new.setDate(d1new.getDate()-1);
    d1maxday = d1new.getDate();
    months += diffdate / d1maxday;
}
else
{
      if(!(d1.getMonth() == d2.getMonth() && d1.getFullYear() == d2.getFullYear()))
    {
        months += 1;
    }
    diffdate = d2day - d1day + 1;
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d2new = new Date(d2year, d2month + 1, 1, 0, 0, 0, 0);
    d2new.setDate(d2new.getDate()-1);
    d2maxday = d2new.getDate();
    months += diffdate / d2maxday;
}

return months;

}

}

#17


1  

below logic will fetch difference in months

下面的逻辑将在几个月内带来不同。

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

#18


0  

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

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

#19


0  

See what I use:

明白我的使用:

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

#20


0  

It also counts the days and convert them in months.

它也计算天数,并在几个月内转换。

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 

#21


-6  

One approach would be to write a simple Java Web Service (REST/JSON) that uses JODA library

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

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

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

to calculate difference between two dates and call that service from javascript.

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

This assumes your back end is in Java.

这假定您的后端是Java。