3

I'm trying to write a logic to convert seconds to the following formats:

  1. HH:MM:SS:MS, where MS is milliseconds
  2. HH:MM:SS;F, where F are the frames

(and not just to HH:MM:SS, therefore this question is different from the others on Stackoverflow)

I have the following logic for getting the HH:MM:SS format currently:

getTime(seconds) {
  let h = Math.floor(seconds / 3600);
  seconds = seconds % 3600;
  let min = Math.floor(seconds / 60);
  seconds = Math.floor(seconds % 60);
  if (seconds.toString().length < 2) seconds = "0" + seconds;
  if (min.toString().length < 2) min = "0" + min;
  return (h + ":" + min + ":" + seconds);
}

but how can I get milliseconds or frames?

Aiguo
  • 3,416
  • 7
  • 27
  • 52
  • Possible duplicate of [JavaScript seconds to time string with format hh:mm:ss](https://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss) – P.S. Jul 29 '17 at 16:30

3 Answers3

2

If seconds is a float, you can take Math.round((seconds - Math.floor(seconds)) * 1000) to get remaining milliseconds. Or Math.round((seconds - Math.floor(seconds)) * fps) where fps is the number of frames per second.

Stephan
  • 2,028
  • 16
  • 19
1

If Your function only takes seconds, then there is no way to get milliseconds out of this information...

You can assume that it is zero milliseconds.

If you want to be accurate to milliseconds, your function should take milliseconds.

simhumileco
  • 31,877
  • 16
  • 137
  • 115
0
var getStringFromMS=(ms,res=[])=>(
   [1000,60,60,24].reduce((rest,curr,i)=>(
     res[3-i]=rest%curr,Math.floor(rest/curr)
   ),ms),res.join(":")
);

In action with current time

Simply iterate over the different periods and reduce the milliseconds to days, while doing that the result is stored in res, which can be joined then simply. You may replace 1000 with frames

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151