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


当前回答

这是一个非常简单的任务,但你们中的一些人直接推荐了Moment.js,或者创建了一些最丑陋的函数来解析一些秒…

transform(time: number): string {
    if (time != null) {
        const hours: number = Math.floor(time / 3600);
        const minutes: number = Math.floor((time - (hours * 3600)) / 60);
        const seconds: number = time - (hours * 3600) - (minutes * 60);
        return [hours, (minutes < 10) ? '0' + minutes : minutes, (seconds < 10) ? '0' + seconds : seconds].join(':');
    } else {
        return '00:00:00';
    }
}

这在任何情况下都适用……

其他回答

对于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];  
}

对于任何使用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);

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

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

我知道这有点老了,但是…

ES2015:

var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}

它将输出:

toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18