Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript seconds to time string with format hh:mm:ss

I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)

I found some useful answers here but they all talk about converting to x hours and x minutes format.

So is there a tiny snippet that does this in jQuery or just raw JavaScript?

like image 388
medk Avatar asked Jun 10 '11 23:06

medk


People also ask

How do you convert HH MM SS to seconds in JavaScript?

const hms = '02:04:33'; const [hours, minutes, seconds] = hms. split(':'); const totalSeconds = (+hours) * 60 * 60 + (+minutes) * 60 + (+seconds); console. log(totalSeconds);

How do you get HH MM SS from seconds?

To convert seconds to HH:MM:SS :Multiply the seconds by 1000 to get milliseconds. Pass the milliseconds to the Date() constructor. Use the toISOString() method on the Date object.

How do you get time in HH MM SS?

To show current time in JavaScript in the format HH:MM:SS, we use the date's toLocaleTimeString method. const d = new Date(); console.

What is HH MM SS format for time?

HH:mm:ss - this format displays a 24-hour digital clock with leading zero for hours. It also displays minutes and seconds.


1 Answers

String.prototype.toHHMMSS = function () {     var sec_num = parseInt(this, 10); // don't forget the second param     var hours   = Math.floor(sec_num / 3600);     var minutes = Math.floor((sec_num - (hours * 3600)) / 60);     var seconds = sec_num - (hours * 3600) - (minutes * 60);      if (hours   < 10) {hours   = "0"+hours;}     if (minutes < 10) {minutes = "0"+minutes;}     if (seconds < 10) {seconds = "0"+seconds;}     return hours+':'+minutes+':'+seconds; } 

You can use it now like:

alert("5678".toHHMMSS()); 

Working snippet:

String.prototype.toHHMMSS = function () {      var sec_num = parseInt(this, 10); // don't forget the second param      var hours   = Math.floor(sec_num / 3600);      var minutes = Math.floor((sec_num - (hours * 3600)) / 60);      var seconds = sec_num - (hours * 3600) - (minutes * 60);        if (hours   < 10) {hours   = "0"+hours;}      if (minutes < 10) {minutes = "0"+minutes;}      if (seconds < 10) {seconds = "0"+seconds;}      return hours + ':' + minutes + ':' + seconds;  }        console.log("5678".toHHMMSS());
like image 134
powtac Avatar answered Sep 20 '22 18:09

powtac