fork download
  1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. import java.time.format.DateTimeParseException;
  4. import java.util.Locale;
  5.  
  6. class Main {
  7. public static void main(String[] args) {
  8. DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
  9. String arr[] = {
  10. "120/12/2013", // 120 will be discarded against MM
  11. "23/12/2013", // Month can not be outside the range 1-12
  12. "Jan/12/2013", // Jan will discarded against MM. Requires MMM
  13. "12/31/2022", // Will be parsed normally
  14. "02/31/2022" // Will be parsed to 2022-02-28
  15. };
  16. for (String s : arr) {
  17. try {
  18. System.out.println("===========================");
  19. System.out.println("Trying to parse " + s + " using the format MM/dd/uuuu");
  20. System.out.println("Parsed to " + LocalDate.parse(s, parser));
  21. } catch (DateTimeParseException e) {
  22. System.out.println(e.getMessage());
  23. // throw e;
  24. }
  25. }
  26. }
  27. }
Success #stdin #stdout 0.17s 55388KB
stdin
Standard input is empty
stdout
===========================
Trying to parse 120/12/2013 using the format MM/dd/uuuu
Text '120/12/2013' could not be parsed at index 2
===========================
Trying to parse 23/12/2013 using the format MM/dd/uuuu
Text '23/12/2013' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 23
===========================
Trying to parse Jan/12/2013 using the format MM/dd/uuuu
Text 'Jan/12/2013' could not be parsed at index 0
===========================
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
Parsed to 2022-02-28