如何使用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;
}
(来源此处)
其他回答
你也可以使用下面的代码:
int ss = nDur%60;
nDur = nDur/60;
int mm = nDur%60;
int hh = nDur/60;
试试这个:
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
你也可以用Sugar。
Date.create().reset().set({seconds: 180}).format('{mm}:{ss}');
这个例子返回'03:00'。
简单的函数转换秒为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;
}
您尝试过向Date对象添加秒数吗?
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);
一个示例: https://jsfiddle.net/j5g2p0dc/5/
更新: 样本链接缺失,所以我创建了一个新的。