我想将持续时间(即秒数)转换为以冒号分隔的时间字符串(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());