Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách chuyển giây sang định dạng HH-MM-SS trong JavaScript

Viết hàm chuyển tổng giây thành chuỗi HH-MM-SS (đệm 0 cho < 10).

Ví dụ

<html>
  <head>
    <title>Chuyển giây sang HH-MM-SS JavaScript</title>
  </head>
  <body>
    <div id="newSeconds"></div>
    <script>
      function convertSeconds(sec) {
        var hrs = Math.floor(sec / 3600);
        var min = Math.floor((sec - hrs * 3600) / 60);
        var seconds = sec - hrs * 3600 - min * 60;
        seconds = Math.round(seconds * 100) / 100;
        var result = (hrs < 10 ? "0" + hrs : hrs);
        result += "-" + (min < 10 ? "0" + min : min);
        result += "-" + (seconds < 10 ? "0" + seconds : seconds);
        return result;
      }
      document.getElementById("newSeconds").innerHTML = convertSeconds(100); // 00-01-40
    </script>
  </body>
</html>