我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
我想转换时间的持续时间,即秒数,以冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都谈到了转换成x小时和x分钟的格式。
那么有一个小片段,这是在jQuery或只是原始JavaScript?
当前回答
如果你是在处理视频长度,这个版本的公认答案会让它看起来更漂亮:
1:37:40(1小时/ 37分钟/ 40秒)
1:00(1分钟)
2:20(2分20秒)
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);
var hourSeparator = ':';
var minuteSeparator = ':';
if(hours == 0){hours = '';hourSeparator = '';}
if (minutes < 10 && hours != 0) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+hourSeparator+minutes+minuteSeparator+seconds;
return time;
}
其他回答
function formatTime(seconds) {
return [
parseInt(seconds / 60 / 60),
parseInt(seconds / 60 % 60),
parseInt(seconds % 60)
]
.join(":")
.replace(/\b(\d)\b/g, "0$1")
}
这是另一个版本,也处理天数:
function FormatSecondsAsDurationString( seconds )
{
var s = "";
var days = Math.floor( ( seconds / 3600 ) / 24 );
if ( days >= 1 )
{
s += days.toString() + " day" + ( ( days == 1 ) ? "" : "s" ) + " + ";
seconds -= days * 24 * 3600;
}
var hours = Math.floor( seconds / 3600 );
s += GetPaddedIntString( hours.toString(), 2 ) + ":";
seconds -= hours * 3600;
var minutes = Math.floor( seconds / 60 );
s += GetPaddedIntString( minutes.toString(), 2 ) + ":";
seconds -= minutes * 60;
s += GetPaddedIntString( Math.floor( seconds ).toString(), 2 );
return s;
}
function GetPaddedIntString( n, numDigits )
{
var nPadded = n;
for ( ; nPadded.length < numDigits ; )
{
nPadded = "0" + nPadded;
}
return nPadded;
}
我最喜欢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"
const secondsToTime = (seconds, locale) => { const date = new date (0); 日期。setHours(0, 0, seconds, 0); 返回date.toLocaleTimeString(地区); } “en”console.log (secondsToTime (3610));
在哪里区域参数(“en”,“de”等)是可选的
主题的变奏。处理个位数秒的方式有点不同
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;
}