使用格式hh:mm:ss的JavaScript秒到时间字符串 [英] JavaScript seconds to time string with format hh:mm:ss
本文介绍了使用格式hh:mm:ss的JavaScript秒到时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想转换一段时间,即以冒号分隔时间字符串的秒数(hh:mm:ss)
I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)
我找到了一些有用的答案这里,但他们都谈到转换为x小时和x分钟格式。
I found some useful answers here but they all talk about converting to x hours and x minutes format.
那么有一个小小的片段在jQuery或原始JavaScript中执行此操作吗?
So is there a tiny snippet that does this in jQuery or just raw JavaScript?
推荐答案
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());
这篇关于使用格式hh:mm:ss的JavaScript秒到时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文