I tried to use DateTimeFormatter for it, but not found way. Duration.parse("") only use special format.
Asked
Active
Viewed 3,905 times
11
-
How about something like http://stackoverflow.com/questions/6403851/parsing-time-strings-like-1h-30min? – cmbuckley Jul 08 '14 at 22:33
-
The problem is I have to use java.time.Duration class, not joda time classes. – roman-v1 Jul 08 '14 at 22:36
-
I found way to parse string to TemporalAccessor, may be there is a way get from it Duration? – roman-v1 Jul 08 '14 at 22:48
-
Can you make use of DateTimeFormatter? – cmbuckley Jul 09 '14 at 08:30
3 Answers
11
You can parse the String yourself and reformat it into the format required by Duration
String value = ... //mm:ss
String[] fields = value.split(":");
return Duration.parse(String.format("P%dM%sS", fields[0], fields[1]));

dkatzel
- 31,188
- 3
- 63
- 67
-
I wanted to use some of facilities of java 8, because format can be changed later, but now it fits. Thanks, dkatzel. – roman-v1 Jul 10 '14 at 21:49
1
The accepted answer guides in the right direction but it has the following problems which may be difficult for a beginner to figure out and correct:
- It does not follow the correct format of
Duration
which starts withPT
. - It should use
%s
instead of%d
forfields[0]
asfields[0]
is of type,String
.
After correcting these two things, the return statement will become
return Duration.parse(String.format("PT%sM%sS", fields[0], fields[1]));
An alternative to splitting and formatting can be to use String#replaceAll
as shown below:
import java.time.Duration;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parseToDuration("09:34"));
System.out.println(parseToDuration("90:34"));
System.out.println(parseToDuration("9:34"));
System.out.println(parseToDuration("0:34"));
System.out.println(parseToDuration("00:04"));
System.out.println(parseToDuration("1:2"));
}
static Duration parseToDuration(String value) {
return Duration.parse(value.replaceAll("(\\d{1,2}):(\\d{1,2})", "PT$1M$2S"));
}
}
Output:
PT9M34S
PT1H30M34S
PT9M34S
PT34S
PT4S
PT1M2S
The regex, (\d{1,2}):(\d{1,2})
has two capturing groups: group(1) is specified with $1
and group(2) is specified with $2
in the replacement string. Each capturing group has \d{1,2}
which specifies 1 to 2 digit(s).

Arvind Kumar Avinash
- 71,965
- 6
- 74
- 110
0
IMHO, java 8 doesn't provide any facility for custom duration parsing.
You should to do it "manually". For example (an efficient way) :
import static java.lang.Integer.valueOf;
import java.time.Duration;
public class DurationParser {
public static Duration parse(String input) {
int colonIndex = input.indexOf(':');
String mm = input.substring(0, colonIndex);
String ss = input.substring(colonIndex + 1);
return Duration.ofMinutes(valueOf(mm)).plusSeconds(valueOf(ss));
}
}

gontard
- 28,720
- 11
- 94
- 117