如何使用JavaScript将秒转换为HH-MM-SS字符串?


当前回答

对于任何使用AngularJS的人来说,一个简单的解决方案是使用date API来过滤值,它会根据请求的格式将毫秒转换为字符串。例子:

<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>

请注意,这需要毫秒,所以如果从秒转换(就像最初的问题一样),可能需要将timerremain乘以1000。

其他回答

在JavaScript Date方法的帮助下,你可以在没有任何外部JavaScript库的情况下做到这一点,如下:

const date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
const result = date.toISOString().slice(11, 19);

或者,按照@Frank的评论;一句话:

new Date(SECONDS * 1000).toISOString().slice(11, 19);

下面是一个函数,根据powtac的答案将秒转换为hh-mm-ss格式

斯菲德尔

/** 
 * 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;
}

示例使用

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

对于HH:MM:SS的特殊情况。MS (eq: "00:04:33.637"), FFMPEG用来指定毫秒。

[-] [HH: MM: SS(打烊……) HH表示小时数,MM表示分钟数 最大值为2位,SS为最大值为2的秒数 位数。最后的m表示SS的十进制值。

/* HH:MM:SS.MS to (FLOAT)seconds ---------------*/ function timerToSec(timer){ let vtimer = timer.split(":") let vhours = +vtimer[0] let vminutes = +vtimer[1] let vseconds = parseFloat(vtimer[2]) return vhours * 3600 + vminutes * 60 + vseconds } /* Seconds to (STRING)HH:MM:SS.MS --------------*/ function secToTimer(sec){ let o = new Date(0) let p = new Date(sec*1000) return new Date(p.getTime()-o.getTime()) .toISOString() .split("T")[1] .split("Z")[0] } /* Example: 7hours, 4 minutes, 33 seconds and 637 milliseconds */ const t = "07:04:33.637" console.log( t + " => " + timerToSec(t) + "s" ) /* Test: 25473 seconds and 637 milliseconds */ const s = 25473.637 // "25473.637" console.log( s + "s => " + secToTimer(s) )

示例使用,毫秒传输计时器:

/* Seconds to (STRING)HH:MM:SS.MS --------------*/ function secToTimer(sec){ let o = new Date(0) let p = new Date(sec*1000) return new Date(p.getTime()-o.getTime()) .toISOString() .split("T")[1] .split("Z")[0] } let job, origin = new Date().getTime() const timer = () => { job = requestAnimationFrame(timer) OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000) } requestAnimationFrame(timer) span {font-size:4rem} <span id="OUT"></span> <br> <button onclick="origin = new Date().getTime()">RESET</button> <button onclick="requestAnimationFrame(timer)">RESTART</button> <button onclick="cancelAnimationFrame(job)">STOP</button>

绑定到媒体元素的示例用法

/* Seconds to (STRING)HH:MM:SS.MS --------------*/ function secToTimer(sec){ let o = new Date(0) let p = new Date(sec*1000) return new Date(p.getTime()-o.getTime()) .toISOString() .split("T")[1] .split("Z")[0] } VIDEO.addEventListener("timeupdate", function(e){ OUT.textContent = secToTimer(e.target.currentTime) }, false) span {font-size:4rem} <span id="OUT"></span><br> <video id="VIDEO" width="400" controls autoplay> <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4"> </video>


在问题之外,那些用php编写的函数:

<?php 
/* HH:MM:SS to (FLOAT)seconds ------------------*/
function timerToSec($timer){
  $vtimer = explode(":",$timer);
  $vhours = (int)$vtimer[0];
  $vminutes = (int)$vtimer[1];
  $vseconds = (float)$vtimer[2];
  return $vhours * 3600 + $vminutes * 60 + $vseconds;
}
/* Seconds to (STRING)HH:MM:SS -----------------*/
function secToTimer($sec){
  return explode(" ", date("H:i:s", $sec))[0];  
}
String.prototype.toHHMMSS = function () {
    var sec_num = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}

使用的例子

alert("186".toHHMMSS());

当我想象一个时钟或计时器时,我会这样做:

const secondsTo_HHMMSS = (seconds) => {
      //format to a readable friendly timer
      let hour = Math.floor(seconds / 3600);
      let minute = Math.floor((seconds % 3600) / 60);
      let second = seconds % 60;

      if(hour.toString().length === 1) {
            hour = `0${hour}`;
      }
      if(minute.toString().length === 1) {
            minute = `0${minute}`;
      }
      if(second.toString().length === 1) {
            second = `0${second}`;
      };

      let timer = `${hour}-${minute}-${second}`;

      return timer;
}