获取时间差JQuery

2019-10-25  本文已影响0人  新世纪好青年
/**
 * 计算两个时间之间的时间差
 * 
 * @param startDate
 *            开始时间
 * @param completeTime
 *            结束时间
 * @returns
 */
function timeDifference(startDate, completeTime) {

    var stime = Date.parse(new Date(startDate));
    var etime = Date.parse(new Date(completeTime));
    var usedTime = etime - stime; // 两个时间戳相差的毫秒数
    var days = Math.floor(usedTime / (24 * 3600 * 1000));
    // 计算出小时数
    var leave1 = usedTime % (24 * 3600 * 1000); // 计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000));
    // 计算相差分钟数
    var leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000));
    // 计算相差秒数
    var leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000)
    if (days == 0 && hours == 0 && minutes == 0 && seconds == 0) {
        var time = minutes + "分" + seconds + "秒";
    } else if (days == 0 && hours == 0 && minutes == 0) {
        var time = minutes + "分" + seconds + "秒";
    } else if (days == 0 && hours == 0) {
        var time = minutes + "分" + seconds + "秒";
    } else if (days == 0) {
        var time = hours + "小时"+ minutes + "分" + seconds + "秒";
    } else {
        var time = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
    }
    return time;
}
上一篇 下一篇

猜你喜欢

热点阅读