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


当前回答

你也可以使用下面的代码:

int ss = nDur%60;
nDur   = nDur/60;
int mm = nDur%60;
int hh = nDur/60;

其他回答

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"

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

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

我认为标准Date对象的任何内置特性都不会以一种比自己做数学更方便的方式为您做这件事。

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;

例子:

let totalSeconds = 28565; let hours = Math.floor(totalSeconds / 3600); totalSeconds %= 3600; let minutes = Math.floor(totalSeconds / 60); let seconds = totalSeconds % 60; console.log("hours: " + hours); console.log("minutes: " + minutes); console.log("seconds: " + seconds); // If you want strings with leading zeroes: minutes = String(minutes).padStart(2, "0"); hours = String(hours).padStart(2, "0"); seconds = String(seconds).padStart(2, "0"); console.log(hours + ":" + minutes + ":" + seconds);

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

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

在一行中,使用T.J.克劳德的解决方案:

secToHHMMSS = seconds => `${Math.floor(seconds / 3600)}:${Math.floor((seconds % 3600) / 60)}:${Math.floor((seconds % 3600) % 60)}`

在一行中,另一个计算天数的解决方案:

secToDHHMMSS = seconds => `${parseInt(seconds / 86400)}d ${new Date(seconds * 1000).toISOString().substr(11, 8)}`

来源:https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

var sec_to_hms = function(sec){
var min, hours;
     sec = sec - (min = Math.floor(sec/60))*60;
     min = min - (hours = Math.floor(min/60))*60;
     return (hours?hours+':':'') + ((min+'').padStart(2, '0')) + ':'+ ((sec+'').padStart(2, '0'));
}
alert(sec_to_hms(2442542));