Difference in Months between two dates in JavaScript

后端 未结 26 2578
南方客
南方客 2020-11-22 17:06

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

Any help would be great :)

相关标签:
26条回答
  • 2020-11-22 18:07

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

    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://stackoverflow.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).

    This will cover the following;

    • 1st Jan to 31st Jan ---> 30days ---> will result in 0 (logical since it is not a full month)
    • 1st Feb to 1st Mar ---> 28 or 29 days ---> will result in 1 (logical since it is a full month)
    • 15th Feb to 15th Mar ---> 28 or 29 days ---> will result in 1 (logical since a month passed)
    • 31st Jan to 1st Feb ---> 1 day ---> will result in 0 (obvious but the mentioned answer in the post results in 1 month)
    0 讨论(0)
  • 2020-11-22 18:07

    Difference in Months between two dates in 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 :

     total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())
    
    0 讨论(0)
  • 2020-11-22 18:08

    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)?

    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.

    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;
    }
    
    0 讨论(0)
  • 2020-11-22 18:08

    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 
    
    0 讨论(0)
  • 2020-11-22 18:09

    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:

    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.

    0 讨论(0)
  • 2020-11-22 18:09

    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;
    }
    
    0 讨论(0)
提交回复
热议问题