ApurvG - 4 years ago 147
Javascript Question

# converting time in seconds to hh:mm:ss:ff

I am using video player in my reactjs project. I get current time of player in seconds. I want to convert the time into format hh:mm:ss:ff where ff is from frames. I have already converted time into format hh:mm:ss but I don't know how to make it show ff also. Assume that I have a video which plays at 24 frames per second and I am getting time like this 126.2344452 secs.

I am doing seconds to hh:mm:ss like this

``````secondsToHms =(d) =>{
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
return ((h > 0 ? h + ":" + (m < 10 ? "00" : "") : "00:") + "0"+ m + ":" + (s < 10 ? "0" : "") + s); }
``````

How to do it?

If you know the fps, the calculation should be pretty straight forward:

1. Get the decimal part of the time with `second % 1`.
2. Multiply it by fps: 0.0 second is "frame 0", and 0.9999 second is "frame fps-1".
3. Add 1 to the zero based frame to make it 1 based.

If you want the total frame instead, simply skip step 1.

``````secondsToHms = ( d, fps = 24 ) => {
const pad2 = txt => ( '0' + Math.floor( txt ) ).substr( -2 ),
h = pad2( d / 3600 ),
m = pad2( d % 3600 / 60 ),
s = pad2( d % 60 ),
f = Math.floor( d % 1 * fps ) + 1;
return `\${h}:\${m}:\${s}:\${f}`;
}
``````

I have taken the liberty to refactor your function. I hope it is still recognisably yours.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download