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

前端 未结 3 855
长情又很酷
长情又很酷 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.");
    
    0 讨论(0)
  • 2020-12-06 06:35

    This worked for me. Verified with Age calculator.

    function calculateAge(){
        ageText = jQuery("#dob").closest(".form-group").find(".age-text");
        ageText.text("");
        level2.dob = jQuery("#dob").val();
        if(!level2.dob) return;
        level2.mdob= moment(level2.dob, 'DD-MM-YYYY');
        if(!level2.mdob.isValid()){
            alert("Invalid date format");
            return;
        }
        level2.targetDate = moment();//TODO: Fill in the target date
        level2.months = level2.targetDate.diff(level2.mdob, 'months'); // Calculate the months
        let years = parseInt(level2.months/12); // A year has 12 months irrespective or leap year or not
        let balanceMonths = level2.months%12; // The balance gives the number of months 
        let days;
        if(!balanceMonths){ // If no balance months, then the date selected lies in the same month
            months = 0; // so months = 0
            days = level2.targetDate.diff(level2.mdob, 'days'); // only the days difference
        }else{
        months = balanceMonths;
        dob_date = level2.mdob.date();
        target_month = level2.targetDate.month();
        construct_date = moment().month(target_month).date(dob_date);
        days = level2.targetDate.diff(construct_date, 'days')+1; // There might be one day missed out. Not sure on UTC
    }
    
    ageText = years +" years " + months+ " months " + days +" days";
    }
    
    0 讨论(0)
  • 2020-12-06 06:38

    Moment.js can't handle this scenario directly. It does allow you to take the difference between two moments, but the result is an elapsed duration of time in milliseconds. Moment does have a Duration object, but it defines a month as a fixed unit of 30 days - which we know is not always the case.

    Fortunately, there is a plugin already created for moment called "Precise Range", which does the right thing. Looking at the source, it does something similar to torazaburo's answer - but it properly accounts for the number of days in the month to adjust.

    After including both moment.js and this plugin (readable-range.js) in your project, you can simply call it like this:

    var m1 = moment('2/22/2013','M/D/YYYY');
    var m2 = moment('4/5/2014','M/D/YYYY');
    var diff = moment.preciseDiff(m1, m2);
    console.log(diff);
    

    The output is "1 year 1 month 14 days"

    0 讨论(0)
提交回复
热议问题