我想将持续时间(即秒数)转换为以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但他们都谈论转换为x小时和x分钟格式。
那么,有没有一个小片段在jQuery或原始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());