The parser generated by DateTimeFormatter.ofPattern
exhibits the following interesting behaviour which is preventing me from writing a pattern to parse a string like 20150100
:
System.out.println(DateTimeFormatter.ofPattern("yyyyMM").parse("201501", YearMonth::from)); // works
System.out.println(DateTimeFormatter.ofPattern("yyyyMM'aa'").parse("201501aa", YearMonth::from)); // works
System.out.println(DateTimeFormatter.ofPattern("yyyyMM'00'").parse("20150100", YearMonth::from));
// java.time.format.DateTimeParseException: Text '20150100' could not be parsed at index 0
I debuged the code, it seems the problem is caused by the year field parsing beyond the end of the string (max width for three y's and more is always 19). However, I don't understand how it could work for the pattern without the '00'
literal at the end.
Is there any way to fix this withing having to use a formatter builder?
Edit:
Since Jarrod below confirmed it's buggy, I did more googling and finally found the bug reports:
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8031085
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8032491
Both are only fixed in Java 9 though......
SimpleDateFormat
supports and the behaviour seems rather like a bug... – HelmholtzSimpleDateFormat
fails the same way as well, because they both rely onDateTimeFormatter
and it is where the bug is. – TarshatarshishSimpleDateFormat
does not fail the same way. It is an independent implementation which does NOT rely onDateTimeFormatter
. Just study the old source code ofSimpleDateFormat
. Both implementations fail for different internal reasons. I would not qualify it as a bug. It is simply a missing feature in both libraries. – Kenon