a) Parsing an expression like mm:ss.S without hours is not possible with the class DateTimeFormatter because such a parser tries to interprete it as point in time, not as duration. The missing hour is a fixed requirement for resolving the result to an instance of LocalTime.
b) You probably want a duration, not a LocalTime. Well, java.time has indeed a class named java.time.Duration but it can only format and parse a subset of ISO-8601-like expressions, for example: PT10M38.2S The pattern you want is not supported. Sorry.
c) Some people suggest a compromise by saying: Interprete LocalTime as kind of duration (not really true!) then parse the expression with a default hour value and finally evaluate the minute-of-hour and second-of-minute and so on. However, such a hacky workaround will only work if you never get time component values greater than 59 minutes or 59 seconds.
d) My external library Time4J supports pattern-based printing and parsing of durations. Example using the class net.time4j.Duration.Formatter:
@Test public void example() throws ParseException { TemporalAmount ta = Duration.formatter(ClockUnit.class, "mm:ss.f") .parse("10:38.2") .toTemporalAmount(); System.out.println(LocalTime.of(5, 0).plus(ta)); // 05:10:38.200 }
The example also demonstrates a bridge to Java-8-classes like LocalTime via the conversion method toTemporalAmount(). If you use net.time4j.PlainTime instead then the bridge is of course not necessary.
Furthermore, one of many features of the time4j-duration-class is controlled normalizing when an expression contains a time component which does not fit into a standard clock scheme like 10 minutes and 68 seconds (= 11min + 8 sec).
@Test public void example2() throws ParseException { net.time4j.Duration dur = Duration.formatter(ClockUnit.class, "mm:ss.f") .parse("10:68.2") .with(Duration.STD_CLOCK_PERIOD); // normalizing System.out.println(PlainTime.of(5, 0).plus(dur)); // 05:11:08.200 }
LocalTimeshould have an hour. What does10:38.0actually mean? If it means 10 minutes 38 seconds, then it is aDuration, not aLocalTime.