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.

I need to convert the second value into a time format in my recent project. 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)
}

// Calling the function.
var time_format = convert_sec_to_time_format(7200) // 7200 is referring second value

console.log(time_format) // 2:00:00 in the 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!

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Comment

Back To Top