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


当前回答

这招很管用:

function secondstotime(secs)
{
    var t = new Date(1970,0,1);
    t.setSeconds(secs);
    var s = t.toTimeString().substr(0,8);
    if(secs > 86399)
        s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    return s;
}

(来源此处)

其他回答

更新(2020):

请使用@Frank的一句话解决方案:

new Date(SECONDS * 1000).toISOString().substring(11, 16)

如果SECONDS<3600并且你只想显示MM:SS,那么使用下面的代码:

new Date(SECONDS * 1000).toISOString().substring(14, 19)

这是目前为止最好的解决办法。


旧的回答:

使用Moment.js库。

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

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

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 <div id="timespan"></div>

您可以使用ES6生成器创建高度可定制的时间字符串。

下面是将数字从给定比例转换为数组的通用函数:

函数toScaledArray (n,尺度){ 函数* g(x, n=0){ 如果(x > 0) { 产生x %(尺度[n] | |∞); 产量* g (Math.floor (x /鳞片[n]), n + 1) } } 返回g (n)[…] } console.log (toScaledArray (6 (10,10))) console.log (toScaledArray(2000年,[30,12])) console.log (toScaledArray(45000年,[12]24日30日))

因此,我们可以使用它来创建时间字符串,如下所示:

> toScaledArray(45000,[60,60]).reverse().join(":")
< '12:30:0'
> toScaledArray(1234,[60,60]).reverse().join(":")
< '20:34'

函数也可以写成一行:

[...(function* g(x,n=0,scales=[60,60]){if(x>0) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().join("-")

上面的函数将省略前导零,如果你想将字符串精确地转换为'HH-MM-SS',你可以使用

[...(function* g(x,n=0,scales=[60,60]){if(x>0||n<3) {yield x%(scales[n]||Infinity); yield* g(Math.floor(x/scales[n]),n+1,scales)}})(45000)].reverse().map(x=>String(x).padStart(2, '0')).join("-")

此外,如果你需要的是'[H:]MM:SS',这里我们有:

Number.prototype.toTimeString = function(){ 返回[…(*函数g (x, n = 0,鳞片= (60 60)){if (x > 0 | | n < 2){收益率x %(尺度[n] | |∞);产量* g (Math.floor (x /鳞片[n]), n + 1,尺度)}})(这)]. map ((x, n) = > n < 2 ?字符串(x) .padStart (2, ' 0 '): x) .reverse () . join(“:”) } console.log (12 (12) .toTimeString ()) console.log (345, (345) .toTimeString ()) console.log (6789, (6789) .toTimeString ())

你也可以有D(ay),甚至M(onth)和Y(ear)(虽然不准确),如下所示:

> toScaledArray(123456789,[60,60,24,30,12]).map((x,n)=>n<2?String(x).padStart(2,'0'):x).reverse().join(":")
< '3:11:18:21:33:09'

这里输出的意思是“3年11个月18天21小时33分9秒”

总之,这是一种高度可定制的将数字转换为可缩放数组的方法,可用于时间字符串转换、人类可读的字节转换甚至纸币的更改。

简单的函数转换秒为hh:mm:ss格式:

function getHHMMSSFromSeconds(totalSeconds) {
    if (!totalSeconds) {
      return '00:00:00';
    }
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor(totalSeconds % 3600 / 60);
    const seconds = totalSeconds % 60;
    const hhmmss = padTo2(hours) + ':' + padTo2(minutes) + ':' + padTo2(seconds);
    return hhmmss;
}

// function to convert single digit to double digit
function padTo2(value) {
    if (!value) {
      return '00';
    }
    return value < 10 ? String(value).padStart(2, '0') : value;
}