2

Can someone help me understand why below works,

DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy[-]MM[-]dd['T']HH[:]mm[:]ss['Z']");
System.out.println(dateTimeFormat.format(dateTimeFormat.parse("2021-0108190739")));

But, below, does not work,

DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("yyyy[-]MM[-]dd['T']HH[:]mm[:]ss['Z']");
System.out.println(dateTimeFormat.format(dateTimeFormat.parse("20210108190739")));

Following exception is generated,

Caused by: java.time.format.DateTimeParseException: Text '20210108190739' could not be parsed, unparsed text found at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1777)
    at Scratch.main(scratch_5.java:9)
    ... 5 more

Are there any workarounds?

Nibras Reeza
  • 127
  • 1
  • 6
  • What exception do you get? – Fildor Jan 08 '21 at 14:09
  • I edited the question to include the exception. – Nibras Reeza Jan 08 '21 at 14:34
  • 4
    The problem is `yyyy` pattern creates a formatter with a year section having a min of 4 digits and a max of 19 digits. You can check it your self by printing out the formater `System.out.println(dateTimeFormat);` Without a separator the first 19 digits are interpreted as the year. See this related post [datetimeformater-with-optional-section](https://stackoverflow.com/questions/31645243/datetimeformater-with-optional-section) or this [java-8-datetimeformatter-parsing-optional-sections](https://stackoverflow.com/questions/51176936/java-8-datetimeformatter-parsing-optional-sections) – Eritrean Jan 08 '21 at 14:45
  • Interesting. Now, only if I could port this to Jackson on Spring Boot without a custom serializer. Thank you for the pointer. Even in the official documentation, it says year is 2 or 4 characters under y/u description. – Nibras Reeza Jan 09 '21 at 16:19

0 Answers0