Converting duration string into milliseconds in Java

Sunny picture Sunny · Mar 14, 2013 · Viewed 11.5k times · Source

I apologize if this has already been discussed.

I have a clip duration in a string:

00:10:17

I would like to convert that to value in milliseconds. (Basically 617000 for the above string)

Is there some API that I could use to do this in one or two steps. On basic way would be to split the string and then add the minutes, seconds and hours.

But is there a shorter way to do this?

Thanks.

Answer

Simon Dorociak picture Simon Dorociak · Mar 14, 2013

Here is one own written possible approach(assumption of same source format always)

String source = "00:10:17";
String[] tokens = source.split(":");
int secondsToMs = Integer.parseInt(tokens[2]) * 1000;
int minutesToMs = Integer.parseInt(tokens[1]) * 60000;
int hoursToMs = Integer.parseInt(tokens[0]) * 3600000;
long total = secondsToMs + minutesToMs + hoursToMs;