Convert seconds to HH-MM-SS with JavaScript?

前端 未结 30 2100
南旧
南旧 2020-11-22 10:05

How can I convert seconds to an HH-MM-SS string using JavaScript?

30条回答
  •  北海茫月
    2020-11-22 10:23

    Here is an extension to Number class. toHHMMSS() converts seconds to an hh:mm:ss string.

    Number.prototype.toHHMMSS = function() {
      var hours = Math.floor(this / 3600) < 10 ? ("00" + Math.floor(this / 3600)).slice(-2) : Math.floor(this / 3600);
      var minutes = ("00" + Math.floor((this % 3600) / 60)).slice(-2);
      var seconds = ("00" + (this % 3600) % 60).slice(-2);
      return hours + ":" + minutes + ":" + seconds;
    }
    
    // Usage: [number variable].toHHMMSS();
    
    // Here is a simple test
    var totalseconds = 1234;
    document.getElementById("timespan").innerHTML = totalseconds.toHHMMSS();
    // HTML of the test
    

提交回复
热议问题