I want to convert this:
00:07:57,685
to seconds.
It should return 00*60 07*60 57,685
The problem is its format I did not manage to write an optimized function.
CodePudding user response:
const input = "00:07:57,685";
const [hours, minutes, secondsRaw] = input.split(/:/g);
const seconds = secondsRaw.replace(",", ".");
let output = 0;
output = parseInt(hours) * 3600;
output = parseInt(minutes) * 60;
output = parseFloat(seconds);
console.log(`${output} seconds`);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Here is a working sample :
function stringTimeToSecond (stringTime) {
// convert from "," float notation to "." float notation
// split your string to [h, m, s]
// reverse to get [s, m, h] to be able to use indice on the reduce method
const stringTimeArray = stringTime.replace(',','.').split(":").reverse();
// 60^0 = 1 for seconds
// 60^1 = 60 for minutes
// 60^2 = 3600 for hours
return stringTimeArray.reduce((timeInSecond, time, i) => {
timeInSecond = time * Math.pow(60, i);
return timeInSecond;
}, 0);
}
Reduce method will iterate through your array and then return your accumulator "timeInSecond". The accumulator is initialized to 0 as the second argument of the reduce function.
CodePudding user response:
I think this might work if i understood your question right:
let timestamp = "00:07:57,685"
let seconds = timestamp.split(":")[2].split(",")[0]