JavaScript seconds to time string with format hh:mm:ss

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)

I found some useful answers here but they all talk about converting to x hours and x minutes format.

So is there a tiny snippet that does this in jQuery or just raw JavaScript?

回答1:

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   

You can use it now like:

alert("5678".toHHMMSS()); 


回答2:

You can manage to do this without any external JS library with the help of JS Date method like following:

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


回答3:

To get the time part in the format hh:MM:ss, you can use this regular expression:

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

(This was mentioned above in same post by someone, thanks for that.)



回答4:

I recommend ordinary javascript, using the Date object:

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 

(Of course, the Date object created will have an actual date associated with it, but that data is extraneous, so for these purposes, you don't have to worry about it.)



回答5:

A Google search turned up this result:

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


回答6:

Variation on a theme. Handles single digit seconds a little differently

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 


回答7:

I like the first answer. Some optimizations for him:

  • source data is a number, there is no need to recalculate.
  • much excess computing

Result code:

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   


回答8:

Using the amazing moment.js library:

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

This allows you to specify any duration be it hours, minutes, seconds, mills, and returns a human readable version.



回答9:

Here is a modern ES6 version:

function formatTime(seconds: number) {   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(':'); } 

Expected results:

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


回答10:

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

result 15:08:03



回答11:

It's pretty easy,

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


回答12:

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

result:

1d 10h 17m 36s 


回答13:

I loved Powtac's answer, but I wanted to use it in Angular, so I created a filter using his code.

.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    0) {             time += '.' + $filter('number')(decimal, decimals).substr(2);         }         return time;     }; }]) 

It's functionally identical, except that I added in an optional decimals field to display fractional seconds. Use it like you would any other filter:

{{ elapsedTime | HHMMSS }} displays: 01:23:45

{{ elapsedTime | HHMMSS : 3 }} displays: 01:23:45.678



回答14:

function formatTime(seconds) {     return [         parseInt(seconds / 60 / 60),         parseInt(seconds / 60 % 60),         parseInt(seconds % 60)     ]         .join(":")         .replace(/\b(\d)\b/g, "0$1") } 


回答15:

I liked Webjins answer the most, so i extended it to display days with a d suffix, made display conditional and included a s suffix on plain seconds:

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

returns "3d 16:32:12" or "16:32:12" or "32:12" or "12s"



回答16:

function toHHMMSS(seconds) {     var h, m, s, result='';     // HOURs     h = Math.floor(seconds/3600);     seconds -= h*3600;     if(h){         result = h

Examples

     toHHMMSS(111);      "01:51"      toHHMMSS(4444);     "01:14:04"      toHHMMSS(33);     "00:33" 


回答17:

A regular expression can be used to match the time substring in the string returned from the toString() method of the Date object, which is formatted as follows: "Thu Jul 05 2012 02:45:12 GMT+0100 (GMT Daylight Time)". Note that this solution uses the time since the epoch: midnight of January 1, 1970. This solution can be a one-liner, though splitting it up makes it much easier to understand.

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


回答18:

Here is yet another version, which handles days also:

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 


回答19:

I think performance wise this is by far the fastest:

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 


回答20:

Here's how I did it. It seems to work fairly well, and it's extremely compact. (It uses a lot of ternary operators, though)

function formatTime(seconds) {   var hh = Math.floor(seconds / 3600),     mm = Math.floor(seconds / 60) % 60,     ss = Math.floor(seconds) % 60;   return (hh ? (hh 

...and for formatting strings...

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


回答21:

I'm personally prefer the leading unit (days, hours, minutes) without leading zeros. But seconds should always be leaded by minutes (0:13), this presentation is easily considered as 'duration', without further explanation (marking as min, sec(s), etc.), usable in various languages (internationalization).

    // 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 

//imitating the server side (.net, C#) duration formatting like:

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


回答22:

You can use Momement.js with moment-duration-format plugin:

var seconds = 3820; var duration = moment.duration(seconds, 'seconds'); var formatted = duration.format("hh:mm:ss"); console.log(formatted); // 01:03:40
 

See also this Fiddle



回答23:

This is how i did it

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) will return '258d 14h 5m 38s'



回答24:

I'd upvote artem's answer, but I am a new poster. I did expand on his solution, though not what the OP asked for as follows

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

To get

04Oct 16:31:28 PDT

This works for me...

But if you are starting with just a time quantity, I use two functions; one to format and pad, and one to calculate:

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 = hr0?dy+"d ":"";   return dy+hr+":"+mi+":"+se; } 


回答25:

If you know the number of seconds you have, this will work. It also uses the native Date() object.

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


回答26:

Non-prototype version of 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   


回答27:

Here is my vision of solution. You can try my snippet below.

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'


回答28:

This version of the accepted answer makes it a bit prettier if you are dealing with video lengths for example:

1:37:40 (1 hour / 37 minutes / 40 seconds)

1:00 (1 minute)

2:20 (2 minutes and 20 seconds)

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 


回答29:

Milliseconds to duration, the simple way:

// To have leading zero digits in strings. function pad(num, size) {     var s = num + "";     while (s.length 

It converts 327577 to 00:05:27.577.

UPDATE

Another way for different scenario:

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 


回答30:

If you use the XDate() library you can use this function

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!