0

I created a function that detects and converts milliseconds to minutes and seconds. What I'd like to do is prepend a zero on either (or both) the minute and second variables if the number comes out to be less than ten. So for instance if I had an integer 184213 which evaluates to 3:4 I'd like it to be 03:04. Is there a short and concise way to do this without having to write out a long conditional or ternary?

msToTime(184213);

function msToTime(milliseconds) {
  var minutes = parseInt(milliseconds/(1000*60)%60),
      seconds = parseInt((milliseconds/1000)%60);
  return minutes + ':' + seconds;
}
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
  • possible duplicate of [How can I create a Zerofilled value using JavaScript?](http://stackoverflow.com/questions/1267283/how-can-i-create-a-zerofilled-value-using-javascript) – jdphenix Apr 10 '15 at 02:10
  • possible duplicate of [Is there a JavaScript function that can pad a string to get to a determined length?](http://stackoverflow.com/questions/2686855/is-there-a-javascript-function-that-can-pad-a-string-to-get-to-a-determined-leng) – PM 77-1 Apr 10 '15 at 02:10

2 Answers2

1

Try this:

msToTime(184213);

function msToTime(milliseconds) {
  var minutes = parseInt(milliseconds/(1000*60)%60),
      seconds = parseInt((milliseconds/1000)%60);
  return ('0' + minutes).slice(-2) + ':' + ('0' + seconds).slice(-2);
}
Omar Elawady
  • 3,300
  • 1
  • 13
  • 17
1

A slightly different approach utilizing Date and slice:

function msToTime(milliseconds) {
  var date = new Date(milliseconds);
  return date.toTimeString().slice(3,8);
}

msToTime(184213);
// outputs: "03:04"

A small caveat is this will of course have a limit of "23:59" and will always be the floor value as any milliseconds value over the minutes will not be shown.

Jason Cust
  • 10,743
  • 2
  • 33
  • 45