Difference in Months between two dates in JavaScript

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

    Sometimes you may want to get just the quantity of the months between two dates totally ignoring the day part. So for instance, if you had two dates- 2013/06/21 and 2013/10/18- and you only cared about the 2013/06 and 2013/10 parts, here are the scenarios and possible solutions:

    var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
    var date2=new Date(2013,9,18);
    var year1=date1.getFullYear();
    var year2=date2.getFullYear();
    var month1=date1.getMonth();
    var month2=date2.getMonth();
    if(month1===0){ //Have to take into account
      month1++;
      month2++;
    }
    var numberOfMonths; 
    

    1.If you want just the number of the months between the two dates excluding both month1 and month2

    numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;
    

    2.If you want to include either of the months

    numberOfMonths = (year2 - year1) * 12 + (month2 - month1);
    

    3.If you want to include both of the months

    numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;
    

提交回复
热议问题