Difference in Months between two dates in JavaScript

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

    function monthDiff(d1, d2) {
    var months, d1day, d2day, d1new, d2new, diffdate,d2month,d2year,d1maxday,d2maxday;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    months = (months <= 0 ? 0 : months);
    d1day = d1.getDate();
    d2day = d2.getDate();
    if(d1day > d2day)
    {
        d2month = d2.getMonth();
        d2year = d2.getFullYear();
        d1new = new Date(d2year, d2month-1, d1day,0,0,0,0);
        var timeDiff = Math.abs(d2.getTime() - d1new.getTime());
              diffdate = Math.abs(Math.ceil(timeDiff / (1000 * 3600 * 24))); 
        d1new = new Date(d2year, d2month, 1,0,0,0,0);
        d1new.setDate(d1new.getDate()-1);
        d1maxday = d1new.getDate();
        months += diffdate / d1maxday;
    }
    else
    {
          if(!(d1.getMonth() == d2.getMonth() && d1.getFullYear() == d2.getFullYear()))
        {
            months += 1;
        }
        diffdate = d2day - d1day + 1;
        d2month = d2.getMonth();
        d2year = d2.getFullYear();
        d2new = new Date(d2year, d2month + 1, 1, 0, 0, 0, 0);
        d2new.setDate(d2new.getDate()-1);
        d2maxday = d2new.getDate();
        months += diffdate / d2maxday;
    }
    
    return months;
    

    }

提交回复
热议问题