Get difference between two dates using jquery

后端 未结 5 2080
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 20:59

Can any one suggest a jQuery plugin for calculating the difference between two dates (dates may contain time also) and show it as \'32 days\', \'13 hours\', \'20 min\' etc?<

5条回答
  •  逝去的感伤
    2021-01-06 21:15

    Here's a pretty simple Javascript implementation I just hacked up. You can do the math to extend this to months or years or remove the plurals for 1 values if needed.

    var dateDiff = function ( d1, d2 ) {
        var diff = Math.abs(d1 - d2);
        if (Math.floor(diff/86400000)) {
            return Math.floor(diff/86400000) + " days";
        } else if (Math.floor(diff/3600000)) {
            return Math.floor(diff/3600000) + " hours";
        } else if (Math.floor(diff/60000)) {
            return Math.floor(diff/60000) + " minutes";
        } else {
            return "< 1 minute";
        }
    };
    
    dateDiff(new Date(1990, 1, 1), new Date(1990, 1, 13)) // -> 12 days
    

提交回复
热议问题