tags:

views:

1332

answers:

5

how can i convert seconds to HH-MM-SS with javascript ?

+6  A: 

Don't you know datejs? it is a must know.

Using datejs, just write something like:

(new Date).clearTime()
          .addSeconds(15457)
          .toString('H:mm:ss');
Cleiton
thx but can you show me how it will help me ??
Yassir
sure, I edited my answer.
Cleiton
thx for the help :)
Yassir
exactly what I'm looking for. Thanks!
huy
+1  A: 

I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.

hours = totalSeconds / 3600;
totalSeconds %= 3600;
minutes = totalSeconds / 60;
seconds = totalSeconds % 60;
T.J. Crowder
yes but you might get this 1:4:43 instead of 01:04:43 !!
Yassir
Oh, this just gives you the numbers. I left the formatting as an exercise for the reader. :)
T.J. Crowder
A: 

I've used this code before to create a simple timespan object:

function TimeSpan(time) {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;

while(time >= 3600)
{
 this.hours++;
 time -= 3600;
}

while(time >= 60)
{
 this.minutes++;
 time -= 60;
}

this.seconds = time;
}

var timespan = new Timespan(3662);
smack0007
A: 

This does the trick:

function secondstotime(secs)
{
    var t = new Date(1970,0,1);
    t.setSeconds(secs);
    var s = t.toTimeString().substr(0,8);
    if(secs > 86399)
     s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    return s;
}

(Sourced from here)

Waggers
+2  A: 
hours = parseInt( totalSec / 3600 ) % 24;
minutes = parseInt( totalSec / 60 ) % 60;
seconds = totalSec % 60;

result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds  < 10 ? "0" + seconds : seconds);
knizz