Difference in Months between two dates in JavaScript

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

    If you need to count full months, regardless of the month being 28, 29, 30 or 31 days. Below should work.

    var months = to.getMonth() - from.getMonth() 
        + (12 * (to.getFullYear() - from.getFullYear()));
    
    if(to.getDate() < from.getDate()){
        months--;
    }
    return months;
    

    This is an extended version of the answer https://stackoverflow.com/a/4312956/1987208 but fixes the case where it calculates 1 month for the case from 31st of January to 1st of February (1day).

    This will cover the following;

    • 1st Jan to 31st Jan ---> 30days ---> will result in 0 (logical since it is not a full month)
    • 1st Feb to 1st Mar ---> 28 or 29 days ---> will result in 1 (logical since it is a full month)
    • 15th Feb to 15th Mar ---> 28 or 29 days ---> will result in 1 (logical since a month passed)
    • 31st Jan to 1st Feb ---> 1 day ---> will result in 0 (obvious but the mentioned answer in the post results in 1 month)

提交回复
热议问题