How to convert second to time format using javascript

How to convert second to time format using javascript

Today I’m going to show quick tips and tricks of JavaScript. Javascript provides all the features to manipulate time and date information from the browser.

In my recent project, I need to convert the second value into a time format. In that project, I have the data in seconds format and need to convert it to 02:00:00 format. I wrote the following function which takes one input as a parameter and outputs it in a specific time format. Sounds interesting, Keep reading.

By using the following JavaScript, we can easily convert the second-to-time format. Let’s take a look at 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 console.log(time_format); // this will display 2:00:00 in browser console.

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

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

Leave a Comment

Back To Top