Problem with parse a LocalDateTime using java 8

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd H:mm:ss");

With this change your program outputs:

2019-05-03T07:05:03

  • A single format pattern letter H will match hour of day in either 1 or two digits. That is, it will accept 7, 07, 13, etc. Two HH on the other hand requires two digits like 07 or 13, so 7 alone cannot be parsed. This was the reason for the exception that you got.
  • Index 11 of your string is not where the space is. It is where the 7 is. Indices are 0-based.
  • As others have mentioned you also need to use uppercase MM for month number. Lowercase mm is for minute of hour.
  • As an aside you don’t necessarily need a DateTimeFormatterBuilder for this case. DateTimeFormatter.ofPattern works OK.

Just out of curiosity, if your formatter is for parsing only, you may omit all repetitions of pattern letters. This works too:

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s");

Normally we would not want this, though. We’d prefer to validate that there are two digits for minutes and seconds, often also for month and day of month. Putting two pattern letters accomplishes that.

Partly related question about mm in the format pattern: Convert LocalDate in DD/MM/YYYY LocalDate [duplicate].

Leave a Comment