I tried to use DateTimeFormatter for it, but not found way. Duration.parse("") only use special format.
-
How about something like stackoverflow.com/questions/6403851/…?cmbuckley– cmbuckley2014-07-08 22:33:25 +00:00Commented Jul 8, 2014 at 22:33
-
The problem is I have to use java.time.Duration class, not joda time classes.roman-v1– roman-v12014-07-08 22:36:12 +00:00Commented Jul 8, 2014 at 22:36
-
I found way to parse string to TemporalAccessor, may be there is a way get from it Duration?roman-v1– roman-v12014-07-08 22:48:17 +00:00Commented Jul 8, 2014 at 22:48
-
Can you make use of DateTimeFormatter?cmbuckley– cmbuckley2014-07-09 08:30:06 +00:00Commented Jul 9, 2014 at 8:30
3 Answers
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("PT%dM%sS", fields[0], fields[1]));
1 Comment
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
Durationwhich starts withPT. - It should use
%sinstead of%dforfields[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).
Comments
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));
}
}