11

I tried to use DateTimeFormatter for it, but not found way. Duration.parse("") only use special format.

roman-v1
  • 728
  • 1
  • 9
  • 21

3 Answers3

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:

  1. It does not follow the correct format of Duration which starts with PT.
  2. It should use %s instead of %d for fields[0] as fields[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