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?

4
  • What exception do you get?
    – Fildor
    Commented Jan 8, 2021 at 14:09
  • I edited the question to include the exception. Commented Jan 8, 2021 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 or this java-8-datetimeformatter-parsing-optional-sections
    – Eritrean
    Commented Jan 8, 2021 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. Commented Jan 9, 2021 at 16:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.