Difference in Months between two dates in JavaScript

后端 未结 26 2869
南方客
南方客 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 17:48

    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.

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

    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.

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

提交回复
热议问题