乐趣区

JS-补时分秒

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var sec = 3829;
      // 格式化时,分,秒

      function Format(sec) {
        const oneHour = 3600;
        const oneMin = 60;

        let hour = (sec / oneHour) | 0;
        let padHour = _padZero({num: hour});
        console.log(padHour);

        let min = ((sec % oneHour) / oneMin) | 0;
        let padMin = _padZero({num: min});
        console.log(padMin);

        let sece = (sec % oneHour) % oneMin | 0;
        let padSec = _padZero({num: sece});
        console.log(padSec)
      }
      /**
       *
       * @param {*} num 需要处理的内容
       * @param {*} Length  希望内容的总长度
       * @param {*} position 希望在左边还是右边进行插入 left or right
       */
      function _padZero({num, length = 2, position = "left"}) {let len = num.toString().length;
        if (position === "left") {while (len < length) {
            num = "0" + num;
            len++;
          }
        } else if (position === "right") {while (len < length) {
            num = num + "0";
            len++;
          }
        }
        return num;
      }

      Format(sec);
    </script>
  </body>
</html>

或者


      function Format2(sec) {
        const oneHour = 3600;
        const oneMin = 60;

        let hour = (sec / oneHour) | 0;
        console.log(hour.toString().padStart(2, "0"));

        let min = ((sec % oneHour) / oneMin) | 0;
        console.log(min.toString().padStart(2, "0"));

        let sece = (sec % oneHour) % oneMin | 0;
        console.log(sece.toString().padStart(2, "0"));
      }

      Format2(sec);
退出移动版