Reputation: 329
I need to convert a string with hours, minutes, seconds and milliseconds "hh:mm:ss:mil" to the floating-point number that HTML audio player uses for currentTime.
I can't find any conversion algorithm that does this! The closest I've found converts to seconds as integers, while I need something like this
"00:00:38:000" -> 38.0 (NOT 2280)
"01:15:02:773" -> 4502.773
My Code so far - but it's wrong
function time2secs(time) {
// 00:03:30 -> 3.5 seconds
var t = time.split(':');
if (t.length < 4) t[3] = 0; // if a missing millisecs, then set it to 0
var seconds = parseInt(t[0]) * 60 * 60 + parseInt(t[1]) * 60 + parseInt(t[2]) + parseInt(t[3]) / 1000;
return seconds / 60;
}
Upvotes: 0
Views: 454
Reputation: 705
Does this code work as you expect?
function time2secs(time) {
var t = time.split(':');
if (t.length < 4) t[3] = 0;
let second = (parseInt(t[0]) * 60 * 60) + (parseInt(t[1]) * 60) + parseInt(t[2]) + (parseInt(t[3]) / 1000);
return t[3] == 0 ? second + ".0" : second;
}
Upvotes: 0
Reputation: 17610
try this
function timeToSec(time){
var arr=time.split(":");
return parseInt(arr[0])*3600+ parseInt(arr[1])*60+ parseInt(arr[2])+ parseInt(arr[3])*0.1000
}
console.log(timeToSec("00:00:38:000" ))
console.log(timeToSec("01:15:02:773" ))
Upvotes: 1