JavaScript display remaining time function

Realization ideas:

  1. The entered time minus the current time is the remaining time, but you cannot subtract hours, minutes and seconds. For example, if you subtract 25 minutes from 05 minutes, the result will be negative.
  2. It can be done with a timestamp , the total milliseconds of the user input time minus the total milliseconds of the current time, and the result is the milliseconds of the remaining time.
  3. Convert the total milliseconds of the remaining time into days, hours, minutes, and seconds (time stamps are converted to hours, minutes and seconds).
  4. The conversion formula is as follows:
  d = parseInt(总秒数/60/60/24);     //   计算天数
  h = parseInt(总秒数/60/60 %24)     //   计算小时
  m = parseInt(总秒数/60%60);        //   计算分数
  s = parseInt(总秒数%60);           //   计算当前秒数

Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function countDown(time) {
     
     
            var nowTime = +new Date(); // 返回的是当前时间总的毫秒数
            var inputTime = +new Date(time); // 返回的是用户输入时间总的毫秒数
            var times = (inputTime - nowTime) / 1000; // times是剩余时间总的秒数 
            var d = parseInt(times / 60 / 60 / 24); // 天
            d = d < 10 ? '0' + d : d;
            var h = parseInt(times / 60 / 60 % 24); //时
            h = h < 10 ? '0' + h : h;
            var m = parseInt(times / 60 % 60); // 分
            m = m < 10 ? '0' + m : m;
            var s = parseInt(times % 60); // 当前的秒
            s = s < 10 ? '0' + s : s;
            return d + '天' + h + '时' + m + '分' + s + '秒';
        }
        console.log(countDown('2020-11-11 00:00:00')); //设置的倒计时截止日期为2020年11月11日00点
    </script>
</body>

</html>

Output result:

The current time is:
Insert picture description here
00:00 on November 11, 2020:
Insert picture description here

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109241869