Question

I am trying to find a good solution for converting seconds to time format.

I have this function which works fine for my needs so far.

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

alert(secondstotime(1920));

So you can run this in jsfiddle http://jsfiddle.net/7Pp5z/

So this works great and works for hours etc but i am looking to strip the zeros to the left of the time. Taking the example

i want 00:32:00

to become 32:00 so it looks better that way when outputted to the browser

Can someone tell me the best way to do this or does anyone have another function they could possibly share.

Thanks

Was it helpful?

Solution

put the condition below :

if(s.substr(0, 2) == 00)
        return s.substr(3);

working demo http://jsfiddle.net/7Pp5z/2/

OTHER TIPS

First off you should state your question more clearly.

"Converting Seconds to Time Format" Seconds are one way to represent duration, but some kind of reference is needed to make it relevant.

A.D., UTC, or a duration.

See http://en.wikipedia.org/wiki/ISO_8601 for the win.

Try this in a JavaScript Console:

d = new Date(1920000)
Thu Jan 01 1970 01:32:00 GMT+0100 (Westeuropäische Normalzeit)
d.getUTCMinutes()
32
d.getUTCSeconds()
0

Here's a function to display a time string in the requested format from a given number of seconds [s]:

function showtime(s){
   var time = new Date(new Date('1970/1/1 00:00').setSeconds(s))
                .toTimeString().split(' ')[0].split(':');
   return (+time[0] ? time[0]+':' : '') +
          (+time[1] || +time[0]  ? time[1] +':' : '') +
           time[2];
}

You can find a demonstration in this jsFiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top