I am getting a video length value as ticks from web server. I want to display it in a "hh:mm:ss" format. How can I do this in JavaScript?
Assuming that ticks are in seconds (you can convert them to seconds first if they aren't), you can get to the desired format by finding the number of whole minutes and hours in the time span, then taking the remaining seconds. The modulo operator is useful here, as is the fact that an hour is 3600 seconds, and a minute is 60 seconds:
function displayTime(ticksInSecs) {
var ticks = ticksInSecs;
var hh = Math.floor(ticks / 3600);
var mm = Math.floor((ticks % 3600) / 60);
var ss = ticks % 60;
alert( pad(hh, 2) + ":" + pad(mm, 2) + ":" + pad(ss, 2) );
}
function pad(n, width) {
var n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}
See this answer for how to pad a number with leading zeros in JS (the method above is derived from this answer).
This is an old question, but I was not happy with any of the answers.
Tick sizes for media come in many durations, so some assumptions need to be made in order to answer the question.
As the desired answer is in seconds, minutes and hours, the first step is to convert the "tick" value to seconds.
seconds = ticks / tickspersecond
For example, if the ticks were in milliseconds, then the conversion would be
seconds = ticks / 1000
hour = seconds / secondsperhour
=> hour = seconds / 3600
minute = seconds / secondsperminute modulus minutesperhour
=> minute = (seconds / 60) % 60)
second = seconds modulus secondsperminute
=> second = seconds % 60
e.g.
function pad2(number){
number = '0' + number;
return number.substr(number.length - 2);
}
Note: Due to floating point errors, you need to apply Math.floor to both the hour and minute values. You could put Math.floor
into the pad2
function if you want to shorten the main code.
// Assume milliseconds for now
var seconds = ticks / 1000;
var hour = Math.floor(seconds / 3600);
var minute = Math.floor((seconds / 60) % 60);
var second = seconds % 60;
var result = pad2(hour) + ':' + pad2(minute) + ':' + pad2(second)
Note: For the sake of the demo I added % 24
(modulus hoursperday
) to the hours display as the hours since 1971 is a "big" number - so will not format to 2 decimal places :)
JSfiddle Demo: https://jsfiddle.net/TrueBlueAussie/x2s77gzu/
or if you want to put Math.floor
in the pad2
https://jsfiddle.net/TrueBlueAussie/x2s77gzu/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With