Difference in Months between two dates in JavaScript

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

提交回复
热议问题