Consider the following date:
String date = "2391995";
String patt = "ddMyyyy";
Using the pattern provided, we can see that date represents September 23, 1995.
But consider what happens when trying to parse it - first the old way, and then the Java 8+ way:
Date dd = new SimpleDateFormat(patt).parse(date);
System.out.println(dd);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(patt);
LocalDate d = LocalDate.parse(date, formatter);
System.out.println(d);
Output:
Sat Sep 23 00:00:00 EDT 1995
Exception in thread "main" java.time.format.DateTimeParseException: Text '2391995' could not be parsed at index 7
...
As we can see, the old way, using SimpleDateFormat works as intended. But when using DateTimeFormatter and LocalDate.parse, an error occurs. Why is this?
The reason the pattern ddMyyyy works with SimpleDateFormat but not with DateTimeFormatter is due to the differences in pattern symbols and their interpretation between these two classes.
SimpleDateFormat and DateTimeFormatter are used to parse and format dates, but they have different sets of pattern symbols and behaviors.
In SimpleDateFormat, the M pattern symbol represents the month in numeric form, and it is intended to handle both single and double-digit months. So, in your original pattern ddMyyyy, the M symbol was interpreted as a single-digit month, and that's why it worked with the input "2391995" (assuming it's meant to be "23/9/1995").
On the other hand, in DateTimeFormatter, the M pattern symbol is specifically intended for parsing single or double-digit months, but it requires a month value that includes a leading zero for single-digit months. Since your input "2391995" has a single-digit month (9), it does not have a leading zero, and that's why the pattern ddMyyyy didn't work as expected.
Like I said, to solve you can include a leading zero, but you can also split the values this way:
String date = "23 9 1995";
String patt = "dd M yyyy";
Check this out:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With