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?
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 formaterSystem.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