Use the Duration
class from java.time (the modern Java date and time API):
String[] times = {
"05:12:02",
"19:12:52",
"40:12:14",
"56:54:10",
"41:12:12"
};
Duration timeSum = Duration.ZERO;
for (String time : times) {
// reformat to ISO 8601
time = time.replaceFirst("(\d{2}):(\d{2}):(\d{2})", "PT$1H$2M$3S");
// add
timeSum = timeSum.plus(Duration.parse(time));
}
System.out.println("Total seconds: " + timeSum.getSeconds());
Output:
Total seconds: 585810
The Duration
class cannot directly parse your time strings. It parses ISO 8601 standard format, so I use a regular expression for converting 05:12:02
to PT05H12M02S
. Then I feed this into Duration.parse
. You may read the ISO 8601 string as “a period of time of 05 hours 12 minutes 02 seconds”.
Classes meant for dates and times — Date
, Calendar
, LocalTime
, etc. — are ill suited for amounts of time. Date
and Calendar
are furthermore long outdated and poorly designed, so don’t try those. While it wouldn’t be impossible to get through, there are some pitfalls, and even if you succeed, it will be hard to read the code and convince oneself that it is correct.
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, I’m told) 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). The code above was developed and run with
org.threeten.bp.Duration
from the backport.
- 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…