java.time.Duration
public static Duration parseDurationString(String durationString) {
String[] components = durationString.split("\\s+");
Duration result = Duration.ZERO;
for (String component : components) {
result = result.plus(Duration.parse("PT" + component));
}
return result;
}
I am assuming that your string represent a duration, an amount of time. Not a time of day, so LocalTime
used in a couple of the answers is the wrong class to use. Represent it in a Duration
object. Also not as a count of milliseconds since numbers like 37512000 are hard to read and make sense of.
Use the method above like this:
System.out.println(parseDurationString("10h 25m 12s"));
System.out.println(parseDurationString("2938s 2h 92m"));
Output:
PT10H25M12S
PT4H20M58S
It may take a bit of getting accustomed before it’s very much easier to read than the millisecond value, but you’ll get the hang of it. The latter, for example, you may read as a period of time of 4 hours 20 minutes 58 seconds.
The format is ISO 8601, the international standard. This is also the only format that Duration.parse()
accepts. Fortunately it is very easy to produce it from each component of your input string, we just prepend the PT
. After having split the string at whitespace, that is.
You may think twice before allowing your user to input the amount of time as 2938s 2h 92m
, though. It could get confusing for himself or herself. A not so loose format may be more manageable. Make your own experiments with your own users if you can get an opportunity.
If you need the duration in milliseconds for an API that doesn’t accept a Duration
, you need to convert, of course. Fortunately it’s easy.
System.out.println(parseDurationString("10h 25m 12s").toMillis());
It yields what you said you wanted:
37512000
Links