2

I'm looking to turn 165 seconds into 2:40 not 0:2:45

The function needs to be able to adapt to how large the seconds value is.

I know there's infinite ways to do this, but I'm looking for a clean way to do it without any external libraries other than jQuery.

tim
  • 127
  • 1
  • 7
  • 1
    If you don't want to use external libraries, why then use the `jquery` tag? – KooiInc May 26 '11 at 06:40
  • Oh, jQuery happens to be on the page so I can use jQuery. I forgot it was an external library haha – tim May 26 '11 at 07:06

3 Answers3

4

Something like: [Math.floor(165/60),165%60].join(':') should work. Actually, it's 2:45 ;~)

[edit] based on your comment a function to convert seconds into a (zero padded, hours trimmed) hr:mi:se string

function hms(sec){
 var   hr = parseInt(sec/(60*60),10)
     , mi = parseInt(sec/60,10)- (hr*60)
     , se = sec%60;
 return [hr,mi,se]
         .join(':')
         .replace(/\b\d\b/g,
            function(a){ 
             return Number(a)===0 ? '00' : a<10? '0'+a : a; 
            }
          )
         .replace(/^00:/,'');
}
alert(hms(165)); //=> 02:45
alert(hms(3850)); //=> 01:04:10
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Sir, your method returns "64:10" for 3850 seconds, I'm looking for a return value of 1:04:10. Thanks for catching the typo! – tim May 26 '11 at 07:06
0

Check this answer : Convert seconds to HH-MM-SS with JavaScript?

hours = totalSeconds / 3600;
totalSeconds %= 3600;
minutes = totalSeconds / 60;
seconds = totalSeconds % 60;
Community
  • 1
  • 1
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

Try something like this (i've included padding to format the digits to two characters each):

String.prototype.padLeft = function(n, pad)
{
    t = '';
    if (n > this.length){
        for (i = 0; i < n - this.length; i++) {
            t += pad;
        }
    }
    return t + this;
}

var seconds = 3850;
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor(seconds % 3600 / 60);

var time = [hours.toString().padLeft(2, '0'), 
            minutes.toString().padLeft(2, '0'), 
            (seconds % 60).toString().padLeft(2, '0')].join(':');
tobias86
  • 4,979
  • 1
  • 21
  • 30