Radicate Radicate - 1 year ago 90
Javascript Question

Efficiently convert string based time into milliseconds

I was given a challenge, to create a function that'd convert a string based time into milliseconds.

That's the string format I was given:


So this value for example will need to return 3010220.


The function needs to be short and one lined.
I'd love to know where I could improve the function below as it didn't pass the criteria. how can this be turned into a one liner?

function toMilliseconds(time){
return time.match(/[0-9]+/g).map(function(val,s,a){
return s != 3 ? +val * ((Math.pow(60,a.length - s -2) * 1000)) : +val;
return a+b;

Answer Source

There are many different ways.

This is the shortest way I can think of (using ES6):

var str = "0:50:10.220";

var ms = (s=>1E3*s[2]+6E4*s[1]+36E5*s[0])(str.split(':'));


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