Difference in Months between two dates in JavaScript

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

    Following code returns full months between two dates by taking nr of days of partial months into account as well.

    var monthDiff = function(d1, d2) {
      if( d2 < d1 ) { 
        var dTmp = d2;
        d2 = d1;
        d1 = dTmp;
      }
    
      var months = (d2.getFullYear() - d1.getFullYear()) * 12;
      months -= d1.getMonth() + 1;
      months += d2.getMonth();
    
      if( d1.getDate() <= d2.getDate() ) months += 1;
    
      return months;
    }
    
    monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
    > 1
    
    monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
    > 0
    
    monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
    > 0
    

提交回复
热议问题