Converting Seconds to Time Format

风流意气都作罢 提交于 2019-12-11 04:54:08

问题


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


回答1:


put the condition below :

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

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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/18417300/converting-seconds-to-time-format

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