Search code examples
java-8java-timedatetimeformatter

While parsing date with upper case month name I get java.time.format.DateTimeParseException


I have few lines of code as shown below

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yy");
formatter = formatter.withLocale( Locale.getDefault() );  
LocalDate date = LocalDate.parse("11-NOV-20", formatter);

Which gives below exception

 Exception in thread "main" java.time.format.DateTimeParseException: Text '11-NOV-20' could not be parsed at index 3
        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 src.DateTimeTest.main(DateTimeTest.java:30)

If I change the Month from NOV to Nov it works fine. I am getting this value from the database table. Do I have to change it programatically or there is any way to handle it?


Solution

  • you can configure your DateTimeFormatter to ignore cases

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .parseCaseInsensitive()
                    .appendPattern("dd-MMM-yy")
                    .toFormatter(Locale.getDefault());