JavaScript中处理时间差

ES6版本

const countdown = (endTime, includeSeconds = true) => {
    // 获取当前时间
    const now = new Date();
    // 将传入的结束时间字符串转换为日期对象
    const endDateTime = new Date(endTime);
 
    // 检查传入的时间字符串是否只包含日期(不包含时分秒)
    if (endTime.trim().split(' ').length === 1) {
        // 如果只有日期,则将时间设置为该日期的午夜(00:00:00)
        endDateTime.setHours(0, 0, 0, 0);
    }
 
    // 计算当前时间与结束时间的时间差(单位:毫秒)
    const timeDifference = endDateTime - now;
 
    // 计算剩余的天数、小时数、分钟数和秒数
    const days = Math.floor(timeDifference / (24 * 3600 * 1000));
    const hours = Math.floor((timeDifference % (24 * 3600 * 1000)) / (3600 * 1000));
    const minutes = Math.floor((timeDifference % (3600 * 1000)) / (60 * 1000));
 
    // 构建倒计时对象
    const countdownObject = {
        days,
        hours,
        minutes,
    };
    
    // 根据includeSeconds参数决定是否包含秒数
    if (includeSeconds) {
        countdownObject.seconds = Math.floor((timeDifference % (60 * 1000)) / 1000);
    }
    
    return countdownObject;
}
 
console.log(countdown('2078-01-28')); // {days: 19775, hours: 8, minutes: 41, seconds: 9}
console.log(countdown('2078-01-28 12:30:00')); // {days: 19775, hours: 21, minutes: 11, seconds: 9}
console.log(countdown('2078-01-28', false)); // {days: 19775, hours: 8, minutes: 41}

ES5版本 

function countdown(endTime, includeSeconds) {
    // 设置默认值,如果includeSeconds未定义,则默认为true
    includeSeconds = typeof includeSeconds !== 'undefined' ? includeSeconds : true;

    // 获取当前时间
    var now = new Date();
    // 将传入的结束时间字符串转换为日期对象
    var endDateTime = new Date(endTime);

    // 检查传入的时间字符串是否只包含日期(不包含时分秒)
    if (endTime.trim().split(' ').length === 1) {
        // 如果只有日期,则将时间设置为该日期的午夜(00:00:00)
        endDateTime.setHours(0, 0, 0, 0);
    }

    // 计算当前时间与结束时间的时间差(单位:毫秒)
    var timeDifference = endDateTime - now;

    // 计算剩余的天数、小时数、分钟数和秒数
    var days = Math.floor(timeDifference / (24 * 3600 * 1000));
    var hours = Math.floor((timeDifference % (24 * 3600 * 1000)) / (3600 * 1000));
    var minutes = Math.floor((timeDifference % (3600 * 1000)) / (60 * 1000));

    // 构建倒计时对象
    let countdownObject = {
        days: days,
        hours: hours,
        minutes: minutes,
    };
    
    // 根据includeSeconds参数决定是否包含秒数
    if (includeSeconds) {
        countdownObject.seconds = Math.floor((timeDifference % (60 * 1000)) / 1000);
    }
    
    return countdownObject;
}

console.log(countdown('2078-01-28')); // {days: 19775, hours: 8, minutes: 44, seconds: 47}
console.log(countdown('2078-01-28 12:30:00')); // {days: 19775, hours: 21, minutes: 14, seconds: 47}
console.log(countdown('2078-01-28', false)); // {days: 19775, hours: 8, minutes: 44}

猜你喜欢

转载自blog.csdn.net/qq_38238956/article/details/134802968