Convert seconds to HH-MM-SS with JavaScript?

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

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

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 10:14

    Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here

    jsfiddle

    /** 
     * Convert seconds to hh-mm-ss format.
     * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
    **/
    var SecondsTohhmmss = function(totalSeconds) {
      var hours   = Math.floor(totalSeconds / 3600);
      var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
      var seconds = totalSeconds - (hours * 3600) - (minutes * 60);
    
      // round seconds
      seconds = Math.round(seconds * 100) / 100
    
      var result = (hours < 10 ? "0" + hours : hours);
          result += "-" + (minutes < 10 ? "0" + minutes : minutes);
          result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
      return result;
    }
    

    Example use

    var seconds = SecondsTohhmmss(70);
    console.log(seconds);
    // logs 00-01-10
    

提交回复
热议问题