我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
当前回答
function formatTime(seconds) {
return [
parseInt(seconds / 60 / 60),
parseInt(seconds / 60 % 60),
parseInt(seconds % 60)
]
.join(":")
.replace(/\b(\d)\b/g, "0$1")
}
其他回答
主题的变奏。处理个位数秒的方式有点不同
seconds2time(0) -> "0s"
seconds2time(59) -> "59s"
seconds2time(60) -> "1:00"
seconds2time(1000) -> "16:40"
seconds2time(4000) -> "1:06:40"
function seconds2time (seconds) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
var seconds = seconds - (hours * 3600) - (minutes * 60);
var time = "";
if (hours != 0) {
time = hours+":";
}
if (minutes != 0 || time !== "") {
minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
time += minutes+":";
}
if (time === "") {
time = seconds+"s";
}
else {
time += (seconds < 10) ? "0"+seconds : String(seconds);
}
return time;
}
toHHMMSS的非原型版本:
function toHHMMSS(seconds) {
var sec_num = parseInt(seconds);
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;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
我最喜欢Webjins的答案,所以我扩展了它以显示d后缀的日子,使显示有条件,并包括一个s后缀的普通秒:
function sec2str(t){
var d = Math.floor(t/86400),
h = ('0'+Math.floor(t/3600) % 24).slice(-2),
m = ('0'+Math.floor(t/60)%60).slice(-2),
s = ('0' + t % 60).slice(-2);
return (d>0?d+'d ':'')+(h>0?h+':':'')+(m>0?m+':':'')+(t>60?s:s+'s');
}
返回"3d 16:32:12"或"16:32:12"或"32:12"或"12s"
我喜欢Powtac的答案,但我想在angular.js中使用它,所以我用他的代码创建了一个过滤器。
.filter('HHMMSS', ['$filter', function ($filter) {
return function (input, decimals) {
var sec_num = parseInt(input, 10),
decimal = parseFloat(input) - sec_num,
hours = Math.floor(sec_num / 3600),
minutes = Math.floor((sec_num - (hours * 3600)) / 60),
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;}
var time = hours+':'+minutes+':'+seconds;
if (decimals > 0) {
time += '.' + $filter('number')(decimal, decimals).substr(2);
}
return time;
};
}])
它在功能上是相同的,除了我添加了一个可选的小数字段来显示小数秒。像使用其他过滤器一样使用它:
{{elapsedTime | HHMMSS}}显示:01:23:45
{{elapsedTime | HHMMSS: 3}}显示:01:23:45.678
secToHHMM(number: number) {
debugger;
let hours = Math.floor(number / 3600);
let minutes = Math.floor((number - (hours * 3600)) / 60);
let seconds = number - (hours * 3600) - (minutes * 60);
let H, M, S;
if (hours < 10) H = ("0" + hours);
if (minutes < 10) M = ("0" + minutes);
if (seconds < 10) S = ("0" + seconds);
return (H || hours) + ':' + (M || minutes) + ':' + (S || seconds);
}