如何用js实现日期天数、时分秒的倒计时

js实现天数倒计时

在用js实现倒计时的时候,可以先算出截止日期和今天之间相差的毫秒数,然后进行相应的比例进行day、 month 、hour、minute、second的计算,便可以准确的计算出相差的时间。
倒计时格式为:纯天数倒计时

function CountDown(year, month, day, hours) {
      let now = new Date();
      let endDate = new Date(year, month - 1, day, hours);
      let leftTime = endDate.getTime() - now.getTime();//计算剩余的毫秒数
      if (leftTime <= 0) {
        leftTime = 0;
      }
      let leftsecond = parseInt(leftTime / 1000);//计算剩余的秒数
      let countDay = Math.floor(leftsecond / (60 * 60 * 24));
      return  countDay;
    },
    //直接调用就好了
     CountDown(2050, 12, 31, 24)

倒计时格式为:天数+小时+分钟+秒

function CountDown(year, month, day, hours) {
    let now = new Date();
    let endDate = new Date(year, month - 1, day, hours);
    let leftTime = endDate.getTime() - now.getTime();//计算剩余的毫秒数
    if (leftTime <= 0) {
        leftTime = 0;
    }
    let leftsecond = parseInt(leftTime / 1000);//计算剩余的秒数
     day = Math.floor(leftsecond / (60 * 60 * 24));
    let hour = Math.floor((leftsecond - day * 24 * 60 * 60) / 3600);
    let minute = Math.floor((leftsecond - day * 24 * 60 * 60 - hour * 3600) / 60);
    let second = Math.floor(leftTime / 1000 % 60, 10);
    return `${day}天${hour}小时${minute}分钟${second}秒`;
}
//直接调用即可
CountDown(2050, 12, 31, 24)

猜你喜欢

转载自blog.csdn.net/weixin_44171297/article/details/110096630