4

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
JAVA_CAT
  • 737
  • 3
  • 13
  • 33
  • You are getting that value from a database table? Don’t transfer strings between your database and your Java application. Transfer `LocalDate` objects. See [Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2](https://stackoverflow.com/questions/43039614/insert-fetch-java-time-localdate-objects-to-from-an-sql-database-such-as-h2). – Ole V.V. Jul 13 '21 at 14:32
  • Also assuming that your database strings are always in English, don’t use `Locale.getDefault()` for your formatter. Use `Locale.ROOT` (or another English-speaking locale). – Ole V.V. Jul 13 '21 at 14:35
  • It is a legacy system and in that it uses java.util.Date. – JAVA_CAT Jul 13 '21 at 14:46

1 Answers1

6

you can configure your DateTimeFormatter to ignore cases

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()
                .appendPattern("dd-MMM-yy")
                .toFormatter(Locale.getDefault());
divadpoc
  • 903
  • 10
  • 31