How to calculate date difference in JavaScript?

前端 未结 18 1780
执笔经年
执笔经年 2020-11-22 03:41

I want to calculate date difference in days, hours, minutes, seconds, milliseconds, nanoseconds. How can I do it?

18条回答
  •  长发绾君心
    2020-11-22 04:10

    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 dString = "May, 20, 1984";
    
    var d1 = new Date(dString);
    var d2 = new Date();
    
    document.write("
    Number of days since "+dString+": "+DateDiff.inDays(d1, d2)); document.write("
    Number of weeks since "+dString+": "+DateDiff.inWeeks(d1, d2)); document.write("
    Number of months since "+dString+": "+DateDiff.inMonths(d1, d2)); document.write("
    Number of years since "+dString+": "+DateDiff.inYears(d1, d2));

    Code sample taken from here.

提交回复
热议问题