Convert number of days into years, months, days

后端 未结 6 651
轮回少年
轮回少年 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 07:09

    You can use link shown below , it has more detailed explanation. JSFIDDLE The detailed code is -

    var DateDiff = {
    
        inDays: function(d1, d2) {
            var t2 = d2.getTime();
            var t1 = d1.getTime();
    
            return parseInt((t2-t1)/(24*3600*1000));
        },
    
        inWeeks: function(d1, d2) {
            var t2 = d2.getTime();
            var t1 = d1.getTime();
    
            return parseInt((t2-t1)/(24*3600*1000*7));
        },
    
        inMonths: function(d1, d2) {
            var d1Y = d1.getFullYear();
            var d2Y = d2.getFullYear();
            var d1M = d1.getMonth();
            var d2M = d2.getMonth();
    
            return (d2M+12*d2Y)-(d1M+12*d1Y);
        },
    
        inYears: function(d1, d2) {
            return d2.getFullYear()-d1.getFullYear();
        }
    }
    
    
    var d1 = new Date("01/01/14");
    var d2 = new Date("01/02/15");
    var months= DateDiff.inYears(d1, d2)*12 ;
    var month = DateDiff.inMonths(d1, d2) - months;
    var days = DateDiff.inYears(d1, d2)*365;
    var dy = DateDiff.inDays(d1, d2) - days;
    alert(DateDiff.inYears(d1, d2) + " Year " + month + " Month "+ dy + " Days");
    

    Link

提交回复
热议问题