Javascript : Formatting second to hh:mm:ss example

Some time we require to convert seconds in hh: mm: SS format. For this here I am writing very simple to function to do this.

function second2Time (sec) {
var sec_numb    = parseInt(sec);
var hours   = Math.floor(sec_numb / 3600);
var minutes = Math.floor((sec_numb - (hours * 3600)) / 60);
var seconds = sec_numb - (hours * 3600) - (minutes * 60);

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

For calling using this function just copy in your script/html file and call this function like this.

document.getElementById(?input1?).value = second2time(3000);

or

$(?#input1?).val(second2time(3000));

Leave a Reply

Your email address will not be published. Required fields are marked *