The following is a method that converts millisecond to human-readable time. However I got a comment about it that says it might return unexpected result for some radix.
function msToTime(duration, sign) {
var milliseconds = parseInt((duration % 1000) / 100),
seconds = parseInt((duration / 1000) % 60),
minutes = parseInt((duration / (1000 * 60)) % 60),
hours = parseInt((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? " " + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return minutes + sign + seconds;
}
$("div").text(msToTime(1203400, ":"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
This is the comment I have received: "The parseInt()
function can return undesired and/or unexpected results if the radix is not supplied.Please make sure a radix is used on all parseInt()
instances."
I tried to add day, week, month, year and so on, but I am not sure if that's the right way. Also it is for a duration of music. So there won't be any case for longer than hours I think.
Any idea to make sure the result of the method is always correct?
parseInt() takes a second parameter called radix as its second parameter
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
Since you are dealing with decimal number system, pass the radix as 10 to solve such a problem
parseInt((duration % 1000) / 100, 10)