java.time.Duration, desugaring and String.format()
private String formattedTime(int mCurrentPosition) {
Duration pos = Duration.ofSeconds(mCurrentPosition);
long hours = pos.toHours();
if (hours == 0) {
return String.format("%d:%02d", pos.toMinutes(), pos.toSecondsPart());
} else {
return String.format("%d:%02d:%02d",
hours, pos.toMinutesPart(), pos.toSecondsPart());
}
}
I haven’t got an Android development environment with me, so am not 100 % sure that desugaring can handle this, but I would certainly dare hope so. The toMinutesPart
and toSecondsPart
methods were introduced in Java 9. String.format()
has been around since Java 1.5, so in any case let it do the formatting for you.
See the above method in action:
System.out.println(formattedTime(47));
System.out.println(formattedTime(4747));
Output is:
0:47
1:19:07
Question: Doesn’t java.time.Duration require Android API level 26?
java.time works nicely on both 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 non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
- On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links
Similar questions (no strict duplicates, but loads of helpful information):
Other links: