We help IT Professionals succeed at work.

converting milliseconds to hours, minutes, seconds in javascript

Medium Priority
Last Modified: 2012-05-06
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.
Watch Question


<script type="text/javascript">
var d = new Date();
document.write(d.getHours() + ":" +d.getMinutes()+":" +d.getSeconds() +"<br/>");

Open in new window

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

Ask the Experts

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);

Open in new window

yeah go with the date object, much cleaner.
Or if you want the leading zeros, you have can add them explicitly like this, say:
<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;
Millisec: <input type=text id=ms onchange=cvt();> = <span id=res></span>

Open in new window


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.
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.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

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

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.