我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
当前回答
//secondsToTime();
var t = wachttijd_sec; // your seconds
var hour = Math.floor(t/3600);
if(hour < 10){
hour = '0'+hour;
}
var time = hour+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2);
//would output: 00:00:00 > +100:00:00
即使超过24小时也能保持倒计时
其他回答
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("5678".toHHMMSS());
工作代码片段:
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; } console.log("5678".toHHMMSS());
我认为这是目前为止最快的性能:
var t = 34236; // your seconds
var time = ('0'+Math.floor(t/3600) % 24).slice(-2)+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2)
//would output: 09:30:36
以下是2019年更新的一句话:
//your date
var someDate = new Date("Wed Jun 26 2019 09:38:02 GMT+0100")
var result = `${String(someDate.getHours()).padStart(2,"0")}:${String(someDate.getMinutes()).padStart(2,"0")}:${String(someDate.getSeconds()).padStart(2,"0")}`
//result will be "09:38:02"
function toHHMMSS(seconds) {
var h, m, s, result='';
// HOURs
h = Math.floor(seconds/3600);
seconds -= h*3600;
if(h){
result = h<10 ? '0'+h+':' : h+':';
}
// MINUTEs
m = Math.floor(seconds/60);
seconds -= m*60;
result += m<10 ? '0'+m+':' : m+':';
// SECONDs
s=seconds%60;
result += s<10 ? '0'+s : s;
return result;
}
例子
toHHMMSS(111); "01:51" toHHMMSS(4444); "01:14:04" toHHMMSS(33); "00:33"
function formatTime(seconds) {
return [
parseInt(seconds / 60 / 60),
parseInt(seconds / 60 % 60),
parseInt(seconds % 60)
]
.join(":")
.replace(/\b(\d)\b/g, "0$1")
}