tl;dr
Try DateTimeFormatter.ofPattern while trapping for IllegalArgumentException.
try {
formatter = DateTimeFormatter.ofPattern( input ) ;
} catch ( IllegalArgumentException e ) {
… // Handle exception thrown for invalid input formatting pattern.
}
Better yet, let DateTimeFormatter.ofLocalized… automatically localize instead of you trying to allow troublesome arbitrary format strings.
Localize, instead
Accepting any arbitrary formatting pattern is going to be a problematic headache. Formatting patterns are complicated and subtle.
In addition, many of the formats will require that you also specify a Locale to determine the human language and cultural norms necessary to decide issues such as translation of month name & day-of-week name & so on, abbreviation, capitalization, punctuation, and more.
I suggest you instead let java.time localize. Instead of passing a formatting pattern, you would pass a FormatStyle enum object (or string of its name), and a Locale object. But as I mentioned above, you need to pass a Locale in any event.
Use the FormatStyle and Locale to get a localizing DateTimeFormatter object.
FormatStyle style = FormatStyle.MEDIUM ;
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( style ).withLocale( locale ) ;
LocalDate localDate = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
String output = localDate.format( formatter ) ;
See this code run live at IdeOne.com.
12 juill. 2021
Trap IllegalArgumentException
If you insist on your approach of accepting arbitrary formatting patterns, you can attempt to use that format with DateTimeFormatter class. Call its ofPattern method. Trap for the IllegalArgumentException thrown if the pattern is invalid.
String input = "dd/mm/yyyy" ;
DateTimeFormatter f = null ;
try {
formatter = DateTimeFormatter.ofPattern( input ) ;
} catch ( IllegalArgumentException e ) {
… // Handle exception thrown for invalid input formatting pattern.
}
Beware: As mentioned above, some formats require a Locale. So you should be receiving a locale argument as well as a formatting pattern, and calling DateTimeFormatter.withLocale.