如何使用JavaScript将秒转换为HH-MM-SS字符串?
当前回答
你也可以使用下面的代码:
int ss = nDur%60;
nDur = nDur/60;
int mm = nDur%60;
int hh = nDur/60;
其他回答
下面是一个函数,根据powtac的答案将秒转换为hh-mm-ss格式
斯菲德尔
/**
* Convert seconds to hh-mm-ss format.
* @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
var hours = Math.floor(totalSeconds / 3600);
var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
var seconds = totalSeconds - (hours * 3600) - (minutes * 60);
// round seconds
seconds = Math.round(seconds * 100) / 100
var result = (hours < 10 ? "0" + hours : hours);
result += "-" + (minutes < 10 ? "0" + minutes : minutes);
result += "-" + (seconds < 10 ? "0" + seconds : seconds);
return result;
}
示例使用
var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10
试试这个:
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
您尝试过向Date对象添加秒数吗?
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);
一个示例: https://jsfiddle.net/j5g2p0dc/5/
更新: 样本链接缺失,所以我创建了一个新的。
再来看看这个老话题——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"
...我试图让它使用尽可能少的代码,这是一种很好的一行程序方法。
易于遵循的版本为菜鸟:
var totalNumberOfSeconds = YOURNUMBEROFSECONDS;
var hours = parseInt( totalNumberOfSeconds / 3600 );
var minutes = parseInt( (totalNumberOfSeconds - (hours * 3600)) / 60 );
var seconds = Math.floor((totalNumberOfSeconds - ((hours * 3600) + (minutes * 60))));
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
console.log(result);