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


当前回答

var  timeInSec = "661"; //even it can be string

String.prototype.toHHMMSS = function () { 
   /* extend the String by using prototypical inheritance */
    var seconds = parseInt(this, 10); // don't forget the second param
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    seconds = seconds - (hours * 3600) - (minutes * 60);

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

alert("5678".toHHMMSS());   // "01:34:38"
console.log(timeInSec.toHHMMSS());   //"00:11:01"

我们可以把这个函数写得更短更清晰,但这会降低可读性,所以我们要把它写得尽可能简单,尽可能稳定。

或者你可以在这里检查一下:

其他回答

试试这个:

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

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

再来看看这个老话题——OP表示HH:MM:SS,许多解决方案都很有效,直到你意识到你需要的时间不止24小时。也许你只需要一行代码。给你:

d=(s)=>{f=Math.floor;g=(n)=>('00'+n).slice(-2);return f(s/3600)+':'+g(f(s/60)%60)+':'+g(s%60)}

它返回H+:MM:SS。要使用它,只需使用:

d(91260);     // returns "25:21:00"
d(960);       // returns "0:16:00"

...我试图让它使用尽可能少的代码,这是一种很好的一行程序方法。

已经有很多答案了,但我的要求是:

转换为持续时间(即,应适用于大于24小时的值) 关心的小数秒到给定的十进制精度 如果为零,则截断前面的小时和分钟。

const seconds2duration = ( seconds, decimals=0 ) => { let fraction = ( seconds - Math.floor( seconds ) ).toFixed( decimals ); fraction = decimals === 0 ? '' : fraction.slice( 1 ); const [ hours, mins, secs ] = [ seconds / 3600, seconds % 3600 / 60, seconds % 3600 % 60 ].map( ( x ) => String( Math.floor( x ) ).padStart( 2, '0' ) ); if ( hours === '00' && mins === '00' ) { return secs + fraction; } else if ( hours === '00' ) { return [ mins, secs + fraction ].join( ':' ); } else { return [ hours, mins, secs + fraction ].join( ':' ); } }; console.log(seconds2duration(25*3600 + 0*60 + 41 + 0.333, 0)); // 25:00:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 0)); // 05:41 console.log(seconds2duration(0*3600 + 5*60 + 41 + 0.333, 1)); // 05:41.3 console.log(seconds2duration(0*3600 + 0*60 + 41 + 0.333, 2)); // 41.33

这里有一个转换时间的简单函数,可能会有帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}