Difference in Months between two dates in JavaScript

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

    Calculate the difference between two dates include fraction of month (days).


    var difference = (date2.getDate() - date1.getDate()) / 30 +
        date2.getMonth() - date1.getMonth() +
        (12 * (date2.getFullYear() - date1.getFullYear()));
    

    For example:
    date1: 24/09/2015 (24th Sept 2015)
    date2: 09/11/2015 (9th Nov 2015)
    the difference: 2.5 (months)

提交回复
热议问题