We help IT Professionals succeed at work.

# converting milliseconds to hours, minutes, seconds in javascript

on
Medium Priority
11,482 Views
Could somebody give me some javascript code. Lets say I have a var called varmilliseconds ="7395000". That variable is the number of milliseconds. I want a formula to convert this to the format time 02:03:15. That is 2 hours, 3 minutes and 15 seconds (Which is 7395000 milliseconds).

If somebody could give me the code that would be great. Thanks.
Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Commented:

``````<script type="text/javascript">

var d = new Date();
d.setTime(7395000);
document.write(d+"<br/>");

document.write(d.getHours()+"hours<br/>");
document.write(d.getMinutes()+"minutes<br/>");
document.write(d.getSeconds()+"second<br/>");

document.write(d.getHours() + ":" +d.getMinutes()+":" +d.getSeconds() +"<br/>");

</script>
``````

Not the solution you were looking for? Getting a personalized solution is easy.

CERTIFIED EXPERT

Commented:

Commented:
try this (untested)
``````var milliseconds = parseInt("7395000");
var hours = Math.floor(milliseconds / 3600000);
var minutes = Math.floor((milliseconds - (hours * 3600000)) / 60000);
var seconds = parseInt((milliseconds - (hours * 3600000) - (minutes * 60000)) / 1000);
``````

Commented:
yeah go with the date object, much cleaner.

Commented:
Or if you want the leading zeros, you have can add them explicitly like this, say:
``````<html>
<script language=javascript>
function cvt()
{
var varmilliseconds = document.getElementById('ms').value;    //get millisecs as string
var s= cvtfrom_ms(varmilliseconds);

document.getElementById('res').innerHTML = s;
}
//---------------
function cvtfrom_ms(s)
{
var d = new Date(parseInt(s));

return   to2digits(d.getHours()) + ":" + to2digits(d.getMinutes()) + ":" + to2digits(d.getSeconds());
}
function to2digits(n)
{
if (n > 10) return n;
return "0" + n;
}
</script>
<body>
Millisec: <input type=text id=ms onchange=cvt();> = <span id=res></span>
</body>
</html>
``````

Commented:
Yeah, I will go with fsze88's solution if you don't mind MMDeveloper. It is much cleaner, like you say and accurate.

I have been messing around all today with doing calculations and getting totally confused and I hadn't realised that there are built in functions that will do all the work for you. Such is my level of knowledge.

Thanks fsze88 for enlightening me.

Commented:
no not at all, as soon as I posted my code it hit me (you know I bet there's some date methods that do this already) but it was too late, someone else had already posted them, no worries.
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile