Convert number of days into years, months, days

后端 未结 6 661
轮回少年
轮回少年 2021-01-12 06:21

I have two date pickers that calculates the number of days there are between the two dates. At the moment I\'m outputting the number of days (see code below) which is kind o

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 06:47

    You have a bug in your calculation : it's 0 month. And if you mean d/m/y then 1 year, 1 month, and 0 day old.

    you said between the two dates ( not include) - look here

    Anyway here is the right code which include actually count each month - how many days it has ! ( leap year consideration):

    notice :

    I instantiated it as d/m/yyy. feel free to send right pattern in :

    alert(getAge( new Date(2014,0,1),new Date(2015,0,2)))

    function getAge(date_1, date_2)
    {
      
    //convert to UTC
    var date2_UTC = new Date(Date.UTC(date_2.getUTCFullYear(), date_2.getUTCMonth(), date_2.getUTCDate()));
    var date1_UTC = new Date(Date.UTC(date_1.getUTCFullYear(), date_1.getUTCMonth(), date_1.getUTCDate()));
    
    
    var yAppendix, mAppendix, dAppendix;
    
    
    //--------------------------------------------------------------
    var days = date2_UTC.getDate() - date1_UTC.getDate();
    if (days < 0)
    {
    
        date2_UTC.setMonth(date2_UTC.getMonth() - 1);
        days += DaysInMonth(date2_UTC);
    }
    //--------------------------------------------------------------
    var months = date2_UTC.getMonth() - date1_UTC.getMonth();
    if (months < 0)
    {
        date2_UTC.setFullYear(date2_UTC.getFullYear() - 1);
        months += 12;
    }
    //--------------------------------------------------------------
    var years = date2_UTC.getFullYear() - date1_UTC.getFullYear();
    
    
    
    
    if (years > 1) yAppendix = " years";
    else yAppendix = " year";
    if (months > 1) mAppendix = " months";
    else mAppendix = " month";
    if (days > 1) dAppendix = " days";
    else dAppendix = " day";
    
    
    return years + yAppendix + ", " + months + mAppendix + ", and " + days + dAppendix + " old.";
    }
    
    
    function DaysInMonth(date2_UTC)
    {
    var monthStart = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth(), 1);
    var monthEnd = new Date(date2_UTC.getFullYear(), date2_UTC.getMonth() + 1, 1);
    var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
    return monthLength;
    }
    
    
    alert(getAge(new Date(2014, 0, 1), new Date(2015, 1, 1)))

提交回复
热议问题