ES6版本

function countdown(endTime, includeSeconds = true) {
    // 获取当前时间
    let now = new Date();
    // 将传入的结束时间字符串转换日期对象
    let endDateTime = new Date(endTime);

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

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

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

    // 构建倒计时字符串
    let countdownString = `${days}天${hours}时${minutes}分`;
    // 根据includeSeconds参数决定是否包含秒数
    if (includeSeconds) {
        countdownString += `${seconds}秒`;
    }

    return countdownString;
}

// 示例用法
// countdown('2078-01-28'); // 只有日期
// countdown('2078-01-28 12:30:00'); // 日期和时间
// countdown('2078-01-28', false); // 只有日期,不包含秒数

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));
    var seconds = Math.floor((timeDifference % (60 * 1000)) / 1000);

    // 构建倒计时字符串
    var countdownString = days + '天' + hours + '时' + minutes + '分';
    // 根据includeSeconds参数决定是否包含秒数
    if (includeSeconds) {
        countdownString += seconds + '秒';
    }

    return countdownString;
}

// 示例用法
// countdown('2078-01-28'); // 只有日期
// countdown('2078-01-28 12:30:00'); // 日期和时间
// countdown('2078-01-28', false); // 只有日期,不包含秒数

原文地址:https://blog.csdn.net/qq_38238956/article/details/134802968

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_49980.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注