How to convert second to time format using javascript

How to convert second to time format using javascript

Today I’m going to show you a quick tips and tricks of JavaScript. Sometimes we need to convert second value into time format. For example- You have seconds info like 7200 seconds and you want to convert it 02:00:00 format. Sounds interesting right? By using following JavaScript we can easily convert second to time format. Let’s take a look of that JavaScript function –

JavaScript Function:

 

function convert_sec_to_time_format( time ) {

    if (typeof (time) == 'undefined') {
        return false;
    }

    var hours = Math.floor(time / 3600);
    time -= hours * 3600;

    var minutes = Math.floor(time / 60);
    time -= minutes * 60;

    var seconds = parseInt(time % 60, 10);

    return hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);

}

// Now call the function.
// We need one parameter.
var time_format = convert_sec_to_time_format(7200); // here 7200 is referring second value
alert(time_format); // this will display 2:00:00 in alert box.

 

I hope that quick tips will help you to convert second to time format using JavaScript. Enjoy!

 

Was this information useful? What other tips would you like to read about in the future? Share your comments, feedback and experiences with us by commenting below!

Tags:  

Share It

Related Posts