fork download
  1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. import java.time.format.DateTimeParseException;
  4. import java.time.format.ResolverStyle;
  5. import java.util.Locale;
  6.  
  7. class Main {
  8. public static void main(String[] args) {
  9. DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH)
  10. .withResolverStyle(ResolverStyle.STRICT);
  11. String arr[] = {
  12. "12/31/2022", // Will be parsed normally
  13. "02/31/2022" // Will fail against ResolverStyle.STRICT check
  14. };
  15. for (String s : arr) {
  16. try {
  17. System.out.println("===========================");
  18. System.out.println("Trying to parse " + s + " using the format MM/dd/uuuu");
  19. System.out.println("Parsed to " + LocalDate.parse(s, parser));
  20. } catch (DateTimeParseException e) {
  21. System.out.println(e.getMessage());
  22. // throw e;
  23. }
  24. }
  25. }
  26. }
Success #stdin #stdout 0.16s 51580KB
stdin
Standard input is empty
stdout
===========================
Trying to parse 12/31/2022 using the format MM/dd/uuuu
Parsed to 2022-12-31
===========================
Trying to parse 02/31/2022 using the format MM/dd/uuuu
Text '02/31/2022' could not be parsed: Invalid date 'FEBRUARY 31'