java.time
String durationString = "01:00:07";
durationString = durationString
.replaceFirst("(\\d{2}):(\\d{2}):(\\d{2})", "PT$1H$2M$3S");
Duration dur = Duration.parse(durationString);
System.out.println(dur);
A Duration
outputs this odd string:
PT1H7S
Read as: a period of time of 1 hour 7 seconds.
That string is in standard ISO 8601 format. A Duration
can only parse the standard format. So I am using String.replaceFirst
to convert your string to it.
Let me guess, you need to sum up durations? There’s a plus
method for that:
Duration sum = Duration.ZERO;
sum = sum.plus(dur);
There are also methods for converting to seconds or milliseconds.
Don’t use a date-time class for a duration. It will lead to confusion and errors.
If you absolutely don’t want an external dependency (only until you move to API level 26), hand parse your string into seconds and represent them in an int
. Wrap it in a custom class of your own.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links