Javascript 将秒转换为 HH:MM:SS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5539028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting seconds into HH:MM:SS
提问by shahidaltaf
Possible Duplicate:
convert seconds to HH-MM-SS with javascript ?
Hi,
你好,
I have a float of 16.4534, which is the seconds of a duration of a video. I want to convert this into HH:MM:SS so it would look like 00:00:16.
我的浮点数为 16.4534,这是视频持续时间的秒数。我想将其转换为 HH:MM:SS,因此它看起来像 00:00:16。
Have done a search but haven't found anything relavent.
已经进行了搜索,但没有找到任何相关内容。
Do I need to use a regex?
我需要使用正则表达式吗?
Help much appreciated.
非常感谢帮助。
Thanks in advance.
提前致谢。
回答by Thorben
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
return ('0' + h).slice(-2) + ":" + ('0' + m).slice(-2) + ":" + ('0' + s).slice(-2);
}
document.writeln('secondsToHms(10) = ' + secondsToHms(10) + '<br>');
document.writeln('secondsToHms(30) = ' + secondsToHms(30) + '<br>');
document.writeln('secondsToHms(60) = ' + secondsToHms(60) + '<br>');
document.writeln('secondsToHms(100) = ' + secondsToHms(100) + '<br>');
document.writeln('secondsToHms(119) = ' + secondsToHms(119) + '<br>');
document.writeln('secondsToHms(500) = ' + secondsToHms(500) + '<br>');