javajava-timedatetime-parsing

Java 8 DateTimeFormatter parsing for optional fractional seconds of varying significance


My MCVE (as a TestNG unit test):

public class MyDateTimeFormatterTest {

    private static final String BASE_PATTERN = "yyyy/MM/dd HH:mm:ss";
    private static final DateTimeFormatter FORMATTER =
            DateTimeFormatter.ofPattern(BASE_PATTERN + "[.SSSSSSSSS]");
    private static final LocalDateTime TEST_INPUT =
            LocalDateTime.of(2015, 5, 4, 12, 34, 56, 123456789);

    @DataProvider(name = "test-cases")
    public Iterator<Object[]> getTestCases() {
        return Arrays.asList(testFor("", ChronoUnit.SECONDS),
                testFor(".SSS", ChronoUnit.MILLIS),
                testFor(".SSSSSS", ChronoUnit.MICROS),
                testFor(".SSSSSSSSS", ChronoUnit.NANOS)).iterator();
    }

    @Test(dataProvider = "test-cases")
    public void testWithDefaultResolution(String input, LocalDateTime output) {
        assertThat(FORMATTER.parse(input, LocalDateTime::from), equalTo(output));
    }

    private Object[] testFor(String patternSuffix, TemporalUnit truncatedTo) {
        return new Object[] { DateTimeFormatter.ofPattern(BASE_PATTERN + patternSuffix)
                .format(TEST_INPUT), TEST_INPUT.truncatedTo(truncatedTo) };
    }
}

I am trying to test the parsing of a date-time String with optional fractional seconds of varying significance using DateTimeFormatter. The relevant part of the Javadoc reads:

Fraction: Outputs the nano-of-second field as a fraction-of-second. The nano-of-second value has nine digits, thus the count of pattern letters is from 1 to 9. If it is less than 9, then the nano-of-second value is truncated, with only the most significant digits being output.

Based on my limited understanding, I used [...] to mark the fractional seconds as optional, and since I'm interested in varying significance, I thought I should stick to SSSSSSSSS.

However, the unit test fails at parsing up to milliseconds and microseconds, i.e. the second and third cases. Changing the ResolverStyle to LENIENT does not help here as it fails at the parsing stage, not the resolution.

May I know which approaches should I consider to resolve my problem? Should I be using DateTimeFormatterBuilder to optionally specify each fractional digit (9 times), or is there a 'smarter' way with my pattern?

edit I found my own answer in the end... will still leave this as unanswered for a day and see if there are other approaches or not.


Solution

  • Oh cool, another 15 minutes of troubleshooting yielded this:

    private static final DateTimeFormatter FORMATTER = 
        new DateTimeFormatterBuilder().appendPattern(BASE_PATTERN) // .parseLenient()
            .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true).toFormatter();
    

    edit parseLenient() is optional.