Our client found an interesting bug today. Consider the following method:
final DateTimeFormatter englishFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.ENGLISH);
System.out.println(LocalDate.parse("04/01/17", englishFormatter));
System.out.println(LocalDate.parse("4/1/17", englishFormatter));
final DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.GERMAN);
System.out.println(LocalDate.parse("01.04.17", germanFormatter));
System.out.println(LocalDate.parse("1.4.17", germanFormatter));
(If you don't know, these are indeed correct dates in English and German. I'd even say they're the same date [April 1 2017]. Take a moment to consider what you'd think this application should return.)
What it does return is the following:
Exception in thread "main" java.time.format.DateTimeParseException: Text '1.4.17' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDate.parse(LocalDate.java:400)
at Main.main(Main.java:20)
The English date format works with and without leading zeroes. The German format works only with leading zeroes.
I can't seem to find a property to change this behavior to work correctly.
How can I make the DateTimeFormatter
understand German dates without leading zeroes?
Note: Our application supports multiple locales, so using a specific DateTimeFormatter
(like DateTimeFormatter.ofPattern("d.M.yy")
) is completely out of the question, especially since we want to parse the default date format.