Difference in Months between two dates in JavaScript

后端 未结 26 2579
南方客
南方客 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:10

    If you do not consider the day of the month, this is by far the simpler solution

    function monthDiff(dateFrom, dateTo) {
     return dateTo.getMonth() - dateFrom.getMonth() + 
       (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
    }
    
    
    //examples
    console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
    console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
    console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1

    Be aware that month index is 0-based. This means that January = 0 and December = 11.

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

    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!

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