javaScript计算两个字符串时间的差值(XX天XX时XX分XX秒)

javaScript计算两个字符串时间的差值(XX天XX时XX分XX秒)

在项目中今天需要计算两个字符串时间的差值,今天来记录一下我的解决方法。

function getDiffTime(startTime,endTime){
    var startTimeDate,endTimeDate;
    if(startTime){
        startTimeDate = new Date(startTime.replace(/-/g, "/")).getTime();
    }else{
        startTimeDate = new Date().getTime();
    }
    if(endTime){
        endTimeDate = new Date(endTime.replace(/-/g, "/")).getTime();
    }else{
        endTimeDate = new Date().getTime();
    }
    var diffTime = endTimeDate - startTimeDate;
    var day = diffTime > 0 ? Math.floor(diffTime/1000/60/60/24) : Math.ceil(diffTime/1000/60/60/24);
    var hDistance = diffTime - day * 86400*1000;
    var hour = hDistance > 0 ? Math.floor(hDistance/3600/1000) : Math.ceil(hDistance/3600/1000);
    var sDistance = hDistance - hour * 3600*1000;
    var second = sDistance > 0 ? Math.floor(sDistance/60/1000) : Math.ceil(sDistance/60/1000);
    var mDistance = sDistance - second * 60*1000;
    var minute = mDistance > 0 ? Math.floor(mDistance/1000) : Math.ceil(mDistance/1000);
    return day + "天" + hour + "时" + second + "分" + minute + "秒";
}