Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting duration string into milliseconds in Java

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.

like image 300
Sunny Avatar asked Nov 28 '22 11:11

Sunny


2 Answers

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;
like image 135
Simon Dorociak Avatar answered Dec 10 '22 18:12

Simon Dorociak


java.time.Duration

Use the Duration class.

Duration.between( 
    LocalTime.MIN , 
    LocalTime.parse( "00:10:17" ) 
).toMillis()

milliseconds: 617000

See this code live in IdeOne.com.

See this Answer of mine and this Answer of mine to similar Questions for more explanation of Duration, LocalTime, and a java.time.

Caution: Beware of possible data-loss when converting from possible values of nanoseconds in java.time objects to your desired milliseconds.

like image 37
Basil Bourque Avatar answered Dec 10 '22 18:12

Basil Bourque