How to get difference between 2 Dates in Years, Months and days using moment.js

前端 未结 3 859
长情又很酷
长情又很酷 2020-12-06 05:57

How to get difference between 2 Dates in Years, Months and days using moment.js? For example the difference between 4/5/2014 & 2/22/2013

3条回答
  •  佛祖请我去吃肉
    2020-12-06 06:32

    You hardly need moment.

    d1 = new Date(2014, 3, 5);                // April 5, 2014
    d2 = new Date(2013, 1, 22);               // February 22, 2013
    diff = new Date(
        d1.getFullYear()-d2.getFullYear(), 
        d1.getMonth()-d2.getMonth(), 
        d1.getDate()-d2.getDate()
    );
    

    This takes advantage of the fact that the Date constructor is smart about negative values. For instance, if the number of months is negative, it will take that into account and walk back the year.

    console.log(diff.getYear(), "Year(s),", 
        diff.getMonth(), "Month(s), and", 
        diff.getDate(), "Days.");
    
    >> 1 Year(s), 1 Month(s), and 11 Days. 
    

    Your calculation is wrong--it's not 14 days, it's six remaining days in February and the first five days of April, so it's 11 days, as the computer correctly computes.

    Second try

    This might work better given @MattJohnson's comment:

    dy = d1.getYear()  - d2.getYear();
    dm = d1.getMonth() - d2.getMonth();
    dd = d1.getDate()  - d2.getDate();
    
    if (dd < 0) { dm -= 1; dd += 30; }
    if (dm < 0) { dy -= 1; dm += 12; }
    
    console.log(dy, "Year(s),", dm, "Month(s), and", dd, "Days.");
    

提交回复
热议问题