JavaScript格式为hh:mm:ss的字符串

我想转换一段时间,即秒数冒号分隔的时间字符串(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()); 

要获得格式为hh:MM:ss的时间部分,可以使用以下正则表达式:

 var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1"); 

(这是上面在同一个帖子中提到的人,谢谢。)

你可以通过JS日期方法来完成这个工作,不需要任何外部JS库,如下所示:

  var date = new Date(null); date.setSeconds(SECONDS); // specify value for SECONDS here date.toISOString().substr(11, 8); 

我推荐普通的JavaScript,使用Date对象:

 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); 

(当然,创建的Date对象会有一个实际的日期关联,但是这些数据是无关的,所以出于这些目的,你不必担心。

谷歌搜索出现了这个结果 :

 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; } 

主题的变化。 处理单位数秒有点不同

 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; } 

我喜欢第一个答案。 对他进行一些优化:

  • 源数据是一个数字,不需要重新计算。
  • 多余的计算

结果代码:

 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; } 

使用惊人的moment.js库:

 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); } 

这使您可以指定任何持续时间,例如小时,分钟,秒,磨机,并返回一个人类可读的版本。

这很容易,

 function toTimeString(seconds) { return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0]; } 

new Date().toString().split(" ")[4];

结果15:08:03

 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); 

结果:

 1d 10h 17m 36s 

我喜欢Powtac的答案,但是我想在Angular中使用它,所以我使用他的代码创建了一个过滤器。

 .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 }} {{ elapsedTime | HHMMSS }} 显示: 01:23:45 : 01:23:45 : 01:23:45

{{ elapsedTime | HHMMSS : 3 }} {{ elapsedTime | HHMMSS : 3 }} 显示: 01:23:45.678

这是一个现代ES6版本:

 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 : '0' + m, s > 9 ? s : '0' + s, ].filter(s => s).join(':'); } 

预期成绩:

 expect(formatTime(0)).to.eq('00:00'); expect(formatTime(1)).to.eq('00:01'); expect(formatTime(599)).to.eq('09:59'); expect(formatTime(600)).to.eq('10:00'); expect(formatTime(3600)).to.eq('1:00:00'); expect(formatTime(360009)).to.eq('100:00:09'); 

我最喜欢Webjins回答,所以我扩展它以显示带有后缀的日子,使条件显示,并作为后缀在简单的秒:

 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”

 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; } 

例子

     toHHMMSS(111); 
     “01:51”

     toHHMMSS(4444);
     “1点14分04秒”

     toHHMMSS(33);
     “00:33”

可以使用正则表达式来匹配从Date对象的toString()方法返回的字符串中的时间子字符串,格式如下:“GMT + 0100(GMT Daylight Time) ”。 请注意,这个解决方案使用自1970年1月1日午夜以来的时间。这个解决方案可以是一个单行的,尽管分开它使得它更容易理解。

 function secondsToTime(seconds) { var start = new Date(1970, 1, 1, 0, 0, 0, 0).getTime(); var end = new Date(1970, 1, 1, 0, 0, parseInt(seconds), 0).getTime(); var duration = end - start; return new Date(duration).toString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$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; } 
 function formatTime(seconds) { return [ parseInt(seconds / 60 / 60), parseInt(seconds / 60 % 60), parseInt(seconds % 60) ] .join(":") .replace(/\b(\d)\b/g, "0$1") } 

我认为这是迄今为止最快的表现:

 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 

我个人更喜欢领先的单位(天,小时,分钟)没有前导零。 但是秒数应该总是以分钟为单位(0:13),这个表示很容易被认为是“持续时间”,没有进一步的解释(标记为min,sec(s)等等),可用于各种语言(国际化)。

  // returns (-)dh: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#)持续时间格式如:

  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)); } 

你可以使用Momement.js和moment-duration-format插件:

 var seconds = 3820; var duration = moment.duration(seconds, 'seconds'); var formatted = duration.format("hh:mm:ss"); console.log(formatted); // 01:03:40 
 <!-- Moment.js library --> <script src="ajax/libs/moment.js/2.18.1/moment.min.js"></script> <!-- moment-duration-format plugin --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script> 

这是我做到的

 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'); } 

timeFromSecs(22341938)将返回'258d 14h 5m 38s'

我会赞成阿尔乔姆的回答,但我是一个新的海报。 我确实扩展了他的解决方案,但不是OP要求如下

  t=(new Date()).toString().split(" "); timestring = (t[2]+t[1]+' <b>'+t[4]+'</b> '+t[6][1]+t[7][0]+t[8][0]); 

要得到

04Oct 16:31:28 PDT

这适用于我…

但是如果你只是以一个时间量开始,我使用两个函数; 一个格式化和填充,一个计算:

 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; } 

如果你知道你有多少秒,这将工作。 它也使用本地的Date()对象。

 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; } 

这是我做的。 它似乎工作得很好,而且非常紧凑。 (虽然它使用了很多三元运算符)

 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 } 

…和格式化字符串…

 String.prototype.toHHMMSS = function() { formatTime(parseInt(this, 10)) }; 

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; } 

这是我的解决方案的愿景。 你可以尝试下面的代码片段。

 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' 

接受的答案的这个版本使得它更漂亮,如果你正在处理视频长度,例如:

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; } 

毫秒到持续时间,简单的方法是:

 // 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); } 

它将327577转换为00:05:27.577

UPDATE

另一种方式为不同的情况:

 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 

如果你使用XDate()库,你可以使用这个函数

 function durationString(begin, end) { "use strict"; let calc = begin.clone(); let years = Math.floor(calc.diffYears(end)); calc = begin.addYears(years); let months = Math.floor(calc.diffMonths(end)); calc = begin.addMonths(months); let days = Math.floor(calc.diffDays(end)); calc = begin.addDays(days); let hours = Math.floor(calc.diffHours(end)); calc = begin.addHours(hours); let minutes = Math.floor(calc.diffMinutes(end)); calc = begin.addMinutes(minutes); let seconds = Math.floor(calc.diffSeconds(end)); return years + "Y " + months + "M " + days + "D - " + hours + "h " + minutes + "m "+ seconds + "s"; }