Jul 222013
 

Just a quick snippet of code to convert seconds to hours, minutes, and seconds, with the hours shown optionally.


function fromSeconds(seconds, showHours = false) {
if(showHours) {
var hours = Math.floor(seconds / 3600);
seconds = seconds - hours * 3600;
}
var minutes = (Math.floor(seconds/60) < 10) ? "0" + Math.floor(seconds/60) : Math.floor(seconds/60); var seconds = (seconds % 60 > 9) ? seconds % 60 : "0" + seconds % 60;
if(showHours) {
var timestring = hours+":"+minutes+":"+seconds;
} else {
var timestring = minutes+":"+seconds;
}
return timestring;
}

Share

  4 Responses to “Snippet : Javascript Hours and Minutes From Seconds”

  1. There is a bit easy way to calculate minutes:seconds from seconds:

    function fromSeconds(sec)
    {
    var d=new Date(0,0,0);
    d.setSeconds(+sec);
    return (d.getHours() ? d.getHours()+':' : '')+d.getMinutes()+':'+d.getSeconds();
    }

    Just format output as your taste.

  2. function fromSeconds(sec)
    {
    var d=new Date(0,0,0);
    d.setSeconds(+sec);
    var hours =d.getHours();
    var minutes = d.getMinutes();
    var seconds = d.getSeconds();

    if (hours < 10) {hours = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
    }

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

This site uses Akismet to reduce spam. Learn how your comment data is processed.