Do your strings represent/denote amounts of time? So use the Duration
class. Let’s first write an auxiliary method that parses a string into a Duration
:
private static Duration parseDuration(String timeString) {
// First convert the string to ISO 8601 through a regex
String isoTimeString = timeString.replaceFirst("^(\\d+):(\\d+):(\\d+):(\\d+)$", "P$1DT$2H$3M$4S");
// Then parse into Duration
return Duration.parse(isoTimeString);
}
Duration.parse()
requires ISO 8601 format, it goes like PT1H9M14S
for a period of time of 1 hour 9 minutes 14 seconds. Or optionally P0DT1H9M14S
. The 0D
for 0 days goes before the T
. So I use a regular expression (AKA a regex) to modify your string format into ISO 8601 before parsing it. The $1
, $2
, etc., in the replacement string refer to what was matched inside the round brackets, the so-called groups in the regular expression.
Now we can add the times up:
String[] timeStrings = { "00:1:9:14", "00:3:10:4", "00:3:39:49" };
Duration totalTime = Duration.ZERO;
for (String timeString : timeStrings) {
Duration dur = parseDuration(timeString);
totalTime = totalTime.plus(dur);
}
System.out.println(totalTime);
Output:
PT7H59M7S
7 hours 59 minutes 7 seconds. If you want, you may format it back into your format of 00:7:59:07
. Search for how.
What went wrong in your code?
Your first mistake seems to have been before writing the code: thinking of the times as dates. They are not, and it would not make any sense to add dates. What is the sum of April 7 and December 25?
Mislead by this thinking, you tried to parse into Date
objects. A Date
is a point in time, not an amount of time, so this is wrong. Other than that the Date
class is poorly designed, and the SimpleDateFormat
class that you also tried to use is notoriously troublesome. Fortunately we’ve got no use for them here, and also for dates and times they are long outdated, superseded by java.time, the modern Java date and time API, of which Duration
is but one of many classes.
Links