Difference in Months between two dates in JavaScript

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

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

提交回复
热议问题