JavaScript seconds to time string with format hh:mm:ss
我要将持续时间(即秒数)转换为冒号分隔的时间字符串(hh:mm:ss)
我在这里找到了一些有用的答案,但它们都是关于转换为x小时x分钟格式的。
那么在jquery中是有一个很小的代码片段,还是仅仅是原始的javascript?
1 2 3 4 5 6 7 8 9 10 11 | 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; } |
号
您现在可以像这样使用它:
1 | alert("5678".toHHMMSS()); |
工作代码段:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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()); |
。
在JS日期方法的帮助下,您可以在不使用任何外部JS库的情况下做到这一点,如下所示:
1 2 3 4 | var date = new Date(null); date.setSeconds(45); // specify value for SECONDS here var timeString = date.toISOString().substr(11, 8); console.log(timeString) |
要获得格式为
(有人在同一篇文章中提到了这一点,谢谢。)
1 2 | var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"); console.log(myDate) |
我建议使用普通的javascript,使用日期对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var seconds = 9999; // multiply by 1000 because Date() requires miliseconds var date = new Date(seconds * 1000); var hh = date.getUTCHours(); var mm = date.getUTCMinutes(); var ss = date.getSeconds(); // If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time // if (hh > 12) {hh = hh % 12;} // These lines ensure you have two-digits if (hh < 10) {hh ="0"+hh;} if (mm < 10) {mm ="0"+mm;} if (ss < 10) {ss ="0"+ss;} // This formats your string to HH:MM:SS var t = hh+":"+mm+":"+ss; document.write(t); |
(当然,创建的日期对象将具有与之关联的实际日期,但该数据是无关的,因此出于这些目的,您不必担心它。)
谷歌搜索结果显示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function secondsToTime(secs) { secs = Math.round(secs); var hours = Math.floor(secs / (60 * 60)); var divisor_for_minutes = secs % (60 * 60); var minutes = Math.floor(divisor_for_minutes / 60); var divisor_for_seconds = divisor_for_minutes % 60; var seconds = Math.ceil(divisor_for_seconds); var obj = { "h": hours, "m": minutes, "s": seconds }; return obj; } |
主题变化。处理单个数字秒有点不同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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; } |
。
这是我的看法:
1 2 3 4 5 6 7 8 9 10 | function formatTime(seconds) { const h = Math.floor(seconds / 3600); const m = Math.floor((seconds % 3600) / 60); const s = seconds % 60; return [ h, m > 9 ? m : (h ? '0' + m : m || '0'), s > 9 ? s : '0' + s, ].filter(a => a).join(':'); } |
。
预期结果:
1 2 3 4 5 6 | expect(formatTime(0)).toEqual('0:00'); expect(formatTime(1)).toEqual('0:01'); expect(formatTime(599)).toEqual('9:59'); expect(formatTime(600)).toEqual('10:00'); expect(formatTime(3600)).toEqual('1:00:00'); expect(formatTime(360009)).toEqual('100:00:09'); |
。
我喜欢第一个答案。有一些优化:
源数据是一个数字。不需要额外的计算。
过度计算
结果代码:
1 2 3 4 5 6 7 8 9 10 11 12 | Number.prototype.toHHMMSS = function () { var seconds = Math.floor(this), hours = Math.floor(seconds / 3600); seconds -= hours*3600; var minutes = Math.floor(seconds / 60); seconds -= minutes*60; if (hours < 10) {hours ="0"+hours;} if (minutes < 10) {minutes ="0"+minutes;} if (seconds < 10) {seconds ="0"+seconds;} return hours+':'+minutes+':'+seconds; } |
。
使用神奇时刻.js库:
1 2 3 4 5 6 7 8 9 10 11 12 13 | function humanizeDuration(input, units ) { // units is a string with possible values of y, M, w, d, h, m, s, ms var duration = moment().startOf('day').add(units, input), format =""; if(duration.hour() > 0){ format +="H [hours]"; } if(duration.minute() > 0){ format +="m [minutes]"; } format +=" s [seconds]"; return duration.format(format); } |
号
这允许您指定任何持续时间,无论是小时、分钟、秒、米尔斯,并返回一个人类可读的版本。
1 2 3 4 5 6 7 8 9 | function formatTime(seconds) { return [ parseInt(seconds / 60 / 60), parseInt(seconds / 60 % 60), parseInt(seconds % 60) ] .join(":") .replace(/\b(\d)\b/g,"0$1") } |
号
埃多克斯1〔2〕
结果
很容易,
1 2 3 | function toTimeString(seconds) { return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0]; } |
1 2 3 4 5 | s2t=function (t){ return parseInt(t/86400)+'d '+(new Date(t%86400*1000)).toUTCString().replace(/.*(\d{2}):(\d{2}):(\d{2}).*/,"$1h $2m $3s"); } s2t(123456); |
号
结果:
1 | 1d 10h 17m 36s |
号
我最喜欢Webjins的答案,所以我将其扩展为显示带有d后缀的天数,使显示成为有条件的,并在纯秒中包含s后缀:
1 2 3 4 5 6 7 | 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中使用它,所以我用他的代码创建了一个过滤器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | .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; }; }]) |
号
它的功能完全相同,只是我在可选的小数字段中添加了一个小数点来显示小数秒。像使用其他过滤器一样使用它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function toHHMMSS(seconds) { var h, m, s, result=''; // HOURs h = Math.floor(seconds/3600); seconds -= h*3600; if(h){ result = h<10 ? '0'+h+':' : h+':'; } // MINUTEs m = Math.floor(seconds/60); seconds -= m*60; result += m<10 ? '0'+m+':' : m+':'; // SECONDs s=seconds%60; result += s<10 ? '0'+s : s; return result; } |
号
示例
1 2 3 4 5 6 7 8 | toHHMMSS(111); "01:51" toHHMMSS(4444); "01:14:04" toHHMMSS(33); "00:33" |
号
正则表达式可用于匹配从日期对象的
1 2 3 4 5 6 7 | function secondsToTime(seconds) { const start = new Date(1970, 1, 1, 0, 0, 0, 0).getTime(); const end = new Date(1970, 1, 1, 0, 0, parseInt(seconds), 0).getTime(); const duration = end - start; return new Date(duration).toString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"); } |
。
这里还有另一个版本,它还处理天数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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; } |
我认为这是迄今为止最快的:
1 2 3 | var t = 34236; // your seconds var time = ('0'+Math.floor(t/3600) % 24).slice(-2)+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2) //would output: 09:30:36 |
号
您可以使用以下函数将时间(以秒为单位)转换为
1 2 3 4 5 6 7 8 | var convertTime = function (input, separator) { var pad = function(input) {return input < 10 ?"0" + input : input;}; return [ pad(Math.floor(input / 3600)), pad(Math.floor(input % 3600 / 60)), pad(Math.floor(input % 60)), ].join(typeof separator !== 'undefined' ? separator : ':' ); } |
。
在不传递分隔符的情况下,它使用
1 | time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51 |
如果要使用
1 | time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46 |
。演示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var convertTime = function (input, separator) { var pad = function(input) {return input < 10 ?"0" + input : input;}; return [ pad(Math.floor(input / 3600)), pad(Math.floor(input % 3600 / 60)), pad(Math.floor(input % 60)), ].join(typeof separator !== 'undefined' ? separator : ':' ); } document.body.innerHTML = '[cc lang="javascript"]' + JSON.stringify({ 5.3515555 : convertTime(5.3515555), 126.2344452 : convertTime(126.2344452, '-'), 1156.1535548 : convertTime(1156.1535548, '.'), 9178.1351559 : convertTime(9178.1351559, ':'), 13555.3515135 : convertTime(13555.3515135, ',') }, null, '\t') + ' |
';
1 2 | </P><P>另见这把小提琴。</P><hr><P>块上的字符串有一个新方法:padstart</P>[cc lang="javascript"]const str = '5'; str.padStart(2, '0'); // 05 |
号
下面是一个示例用例:4行javascript中的YouTube持续时间
我就是这样做的。它看起来工作得相当好,而且非常紧凑。(不过它使用了很多三元运算符)
1 2 3 4 5 6 | function formatTime(seconds) { var hh = Math.floor(seconds / 3600), mm = Math.floor(seconds / 60) % 60, ss = Math.floor(seconds) % 60; return (hh ? (hh < 10 ?"0" :"") + hh +":" :"") + ((mm < 10) && hh ?"0" :"") + mm +":" + (ss < 10 ?"0" :"") + ss } |
…对于格式化字符串…
1 2 3 | String.prototype.toHHMMSS = function() { formatTime(parseInt(this, 10)) }; |
。
1 2 3 4 5 6 7 8 9 10 11 | 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); } |
我就是这样做的
1 2 3 4 5 6 7 8 | function timeFromSecs(seconds) { return( Math.floor(seconds/86400)+'d :'+ Math.floor(((seconds/86400)%1)*24)+'h : '+ Math.floor(((seconds/3600)%1)*60)+'m : '+ Math.round(((seconds/60)%1)*60)+'s'); } |
。
TimeFroms秒(22341938)将返回"258d 14h 5m 38s"
您可以将moment.js与moment duration格式插件一起使用:
1 2 3 4 | var seconds = 3820; var duration = moment.duration(seconds, 'seconds'); var formatted = duration.format("hh:mm:ss"); console.log(formatted); // 01:03:40 |
号
1 2 3 4 5 | <!-- Moment.js library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"> <!-- moment-duration-format plugin --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"> |
号
也看这个小提琴
我个人更喜欢没有前导零的引导单元(天、小时、分钟)。但是秒应该总是以分钟(0:13)开头,这个演示文稿很容易被认为是"持续时间",没有进一步的解释(标记为分钟、秒等),可以在各种语言中使用(国际化)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // returns (-)d.h:mm:ss(.f) // (-)h:mm:ss(.f) // (-)m:ss(.f) function formatSeconds (value, fracDigits) { var isNegative = false; if (isNaN(value)) { return value; } else if (value < 0) { isNegative = true; value = Math.abs(value); } var days = Math.floor(value / 86400); value %= 86400; var hours = Math.floor(value / 3600); value %= 3600; var minutes = Math.floor(value / 60); var seconds = (value % 60).toFixed(fracDigits || 0); if (seconds < 10) { seconds = '0' + seconds; } var res = hours ? (hours + ':' + ('0' + minutes).slice(-2) + ':' + seconds) : (minutes + ':' + seconds); if (days) { res = days + '.' + res; } return (isNegative ? ('-' + res) : res); } |
//模仿服务器端(.net,c)的持续时间格式,如:
1 2 3 4 5 6 7 8 | public static string Format(this TimeSpan interval) { string pattern; if (interval.Days > 0) pattern = @"d\.h\:mm\:ss"; else if (interval.Hours > 0) pattern = @"h\:mm\:ss"; else pattern = @"m\:ss"; return string.Format("{0}", interval.ToString(pattern)); } |
号
我赞成阿耳特姆的回答,但我是一个新的海报。我确实扩展了他的解决方案,但不是OP要求的如下内容
1 2 | t=(new Date()).toString().split(""); timestring = (t[2]+t[1]+' '+t[4]+' '+t[6][1]+t[7][0]+t[8][0]); |
号
得到
10月4日16:31:28 PDT
这对我有用…
但如果您只从一个时间量开始,我使用两个函数:一个用于格式化和填充,另一个用于计算:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function sec2hms(timect){ if(timect=== undefined||timect==0||timect === null){return ''}; //timect is seconds, NOT milliseconds var se=timect % 60; //the remainder after div by 60 timect = Math.floor(timect/60); var mi=timect % 60; //the remainder after div by 60 timect = Math.floor(timect/60); var hr = timect % 24; //the remainder after div by 24 var dy = Math.floor(timect/24); return padify (se, mi, hr, dy); } function padify (se, mi, hr, dy){ hr = hr<10?"0"+hr:hr; mi = mi<10?"0"+mi:mi; se = se<10?"0"+se:se; dy = dy>0?dy+"d":""; return dy+hr+":"+mi+":"+se; } |
号
1 2 3 4 5 6 7 8 | //secondsToTime(); var t = wachttijd_sec; // your seconds var hour = Math.floor(t/3600); if(hour < 10){ hour = '0'+hour; } var time = hour+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2); //would output: 00:00:00 > +100:00:00 |
即使超过24小时也要倒计时
毫秒到持续时间,简单的方法是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // To have leading zero digits in strings. function pad(num, size) { var s = num +""; while (s.length < size) s ="0" + s; return s; } // ms to time/duration msToDuration = function(ms){ var seconds = ms / 1000; var hh = Math.floor(seconds / 3600), mm = Math.floor(seconds / 60) % 60, ss = Math.floor(seconds) % 60, mss = ms % 1000; return pad(hh,2)+':'+pad(mm,2)+':'+pad(ss,2)+'.'+pad(mss,3); } |
它将
更新
不同场景的另一种方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | toHHMMSS = function (n) { var sep = ':', n = parseFloat(n), sss = parseInt((n % 1)*1000), hh = parseInt(n / 3600); n %= 3600; var mm = parseInt(n / 60), ss = parseInt(n % 60); return pad(hh,2)+sep+pad(mm,2)+sep+pad(ss,2)+'.'+pad(sss,3); function pad(num, size) { var str = num +""; while (str.length < size) str ="0" + str; return str; } } toHHMMSS(6315.077) // Return 01:45:15.077 |
如果你知道你所拥有的秒数,这将起作用。它还使用本机日期()对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function formattime(numberofseconds){ var zero = '0', hours, minutes, seconds, time; time = new Date(0, 0, 0, 0, 0, numberofseconds, 0); hh = time.getHours(); mm = time.getMinutes(); ss = time.getSeconds() // Pad zero values to 00 hh = (zero+hh).slice(-2); mm = (zero+mm).slice(-2); ss = (zero+ss).slice(-2); time = hh + ':' + mm + ':' + ss; return time; } |
号
如果您处理视频长度,此版本的接受答案会使其更漂亮一些,例如:
1:37:40(1小时37分40秒)
1:00(1分钟)
2:20(2分20秒)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | function secondsToTime(secs) { var hours = Math.floor(secs / (60 * 60)); var divisor_for_minutes = secs % (60 * 60); var minutes = Math.floor(divisor_for_minutes / 60); var divisor_for_seconds = divisor_for_minutes % 60; var seconds = Math.ceil(divisor_for_seconds); if(hours >= 12) { var m= 'pm' ; } else { var m='am' } if(hours-12 >0) { var hrs = hours-12; } else if(hours-12 <0) { var hrs = hours; } var obj = { "h": hrs, "m": minutes, "s": seconds, "a":m }; return obj; } var d = new Date(); var n = d.getHours(); var hms = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds(); // your input string var a = hms.split(':'); // split it at the colons // minutes are worth 60 seconds. Hours are worth 60 minutes. var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); console.log(seconds); console.log(secondsToTime(seconds)) |
号
https://jsfidle.net/jithinksoft/9x6z4sdt/
这是我的解决方案构想。你可以试试下面我的代码片段。
1 2 3 4 5 6 7 8 9 10 11 12 | function secToHHMM(sec) { var d = new Date(); d.setHours(0); d.setMinutes(0); d.setSeconds(0); d = new Date(d.getTime() + sec*1000); return d.toLocaleString('en-GB').split(' ')[1]; }; alert( 'One hour: ' + secToHHMM(60*60) ); // '01:00:00' alert( 'One hour five minutes: ' + secToHHMM(60*60 + 5*60) ); // '01:05:00' alert( 'One hour five minutes 23 seconds: ' + secToHHMM(60*60 + 5*60 + 23) ); // '01:05:23' |
。
下面是它的ES6版本:
1 2 3 4 | export const parseTime = (time) => { // send time in seconds // eslint-disable-next-line let hours = parseInt(time / 60 / 60), mins = Math.abs(parseInt(time / 60) - (hours * 60)), seconds = Math.round(time % 60); return isNaN(hours) || isNaN(mins) || isNaN(seconds) ? `00:00:00` : `${hours > 9 ? Math.max(hours, 0) : '0' + Math.max(hours, 0)}:${mins > 9 ? Math.max(mins, 0) : '0' + Math.max(0, mins)}:${seconds > 9 ? Math.max(0, seconds) : '0' + Math.max(0, seconds)}`;} |
。
1 2 3 4 5 6 | const secondsToTime = (seconds, locale) => { const date = new Date(0); date.setHours(0, 0, seconds, 0); return date.toLocaleTimeString(locale); } console.log(secondsToTime(3610,"en")); |
号
其中locale参数("en"、"de"等)是可选的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /** * Formats seconds (number) to H:i:s format. * 00:12:00 * * When"short" option is set to true, will return: * 0:50 * 2:00 * 12:00 * 1:00:24 * 10:00:00 */ export default function formatTimeHIS (seconds, { short = false } = {}) { const pad = num => num < 10 ? `0${num}` : num const H = pad(Math.floor(seconds / 3600)) const i = pad(Math.floor(seconds % 3600 / 60)) const s = pad(seconds % 60) if (short) { let result = '' if (H > 0) result += `${+H}:` result += `${H > 0 ? i : +i}:${s}` return result } else { return `${H}:${i}:${s}` } } |
号
tohhmmss的非原型版本:
1 2 3 4 5 6 7 8 9 10 11 | 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; } |
我不喜欢在javascript中向标准数据类型添加属性,因此我建议如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | /** * Format a duration in seconds to a human readable format using the notion *"h+:mm:ss", e.g."4:40:78". Negative durations are preceeded by"-". * * @param t Duration in seconds * @return The formatted duration string */ var readableDuration = (function() { // Each unit is an object with a suffix s and divisor d var units = [ {s: '', d: 1}, // Seconds {s: ':', d: 60}, // Minutes {s: ':', d: 60}, // Hours ]; // Closure function return function(t) { t = parseInt(t); // In order to use modulus var trunc, n = Math.abs(t), i, out = []; // out: list of strings to concat for (i = 0; i < units.length; i++) { n = Math.floor(n / units[i].d); // Total number of this unit // Truncate e.g. 26h to 2h using modulus with next unit divisor if (i+1 < units.length) // Tweak substr with two digits trunc = ('00'+ n % units[i+1].d).substr(-2, 2); // …if not final unit else trunc = n; out.unshift(''+ trunc + units[i].s); // Output } (t < 0) ? out.unshift('-') : null; // Handle negative durations return out.join(''); }; })(); |
号
用途:
1 | var str = readableDuration(3808); //"1:03:28" |
号
我还创建了一个更通用的版本。主要区别在于它接受毫秒(JS中的标准时间单位),而输出格式使用空格。