Laca
Laca

Reputation: 33

DateTimeFormatter pattern postfixed by numeric literal only works if a space is present in the pattern

I saw some similar problems, and that bugs were already fixed regarding issues like this. Now I wonder if I am doing something wrong, or this case is still not covered. My problem is that I have to parse a date followed by zeroes, so the pattern would be yyyyMMdd'0000'. However it fails, but if I put a space in it works: yyyy MMdd'0000'

    DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("yyyy MMdd'0000'").toFormatter().withResolverStyle(ResolverStyle.STRICT);
    System.out.println(formatter.parse(formatter.format(ZonedDateTime.now())));
    formatter = new DateTimeFormatterBuilder().appendPattern("yyyyMMdd'0000'").toFormatter().withResolverStyle(ResolverStyle.STRICT);
    System.out.println(formatter.parse(formatter.format(ZonedDateTime.now())));

I know that I could replace the literal part with the hours and minutes patterns, and it would work, but I would like to use it as a validator mechanism on the input, so it should fail on other values, without additional coding. I tried it with Oracle JDK 1.8.0_221 and OpenJDK 13+33

Thanks!

Upvotes: 2

Views: 176

Answers (2)

Alex Salauyou
Alex Salauyou

Reputation: 14348

Looks not very tidy, but works fine for parsing as well as rendering:

DateTimeFormatter df = new DateTimeFormatterBuilder()
    .appendValue(YEAR, 4)
    .appendPattern("MMdd'0000'")
    .toFormatter()
    .withChronology(IsoChronology.INSTANCE)
    .withResolverStyle(ResolverStyle.STRICT);

log.info(LocalDate.parse("201909260000", df).toString());  // 2019-09-26
log.info(df.format(LocalDate.of(2019, 9, 26)));            // 201909260000

Upvotes: 1

Ilya Sereb
Ilya Sereb

Reputation: 2571

You almost got it. Just do MMMM.

formatter = new DateTimeFormatterBuilder()
        .appendPattern("yyyyMMMMdd'0000'")
        .toFormatter()
        .withResolverStyle(ResolverStyle.STRICT);

Upvotes: 3

Related Questions