0

How do I make sure that the input date has the correct month and day? ex 2021-99-99, obviously there is no such month 99 day 99. How do I make sure the input month number is within 12 and the correct days corresponded with the month?

Minimal reproducible code example:

SimpleDateFormat dateInput = new SimpleDateFormat("yyyy-MM-dd");

// In the real world the string will be entered by the user
String strDate = "2021-99-99";

try {
    Date date = (Date) dateInput.parse(strDate); 
    System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
} catch (ParseException e) {
    System.out.println("Wrong format");
} catch (DateTimeParseException e) {
    e.printStackTrace();
    System.out.println("Invalid date");
}

Expected result: an exception and an error message being printed from either of the catch blocks.

Observed output:

2029-06-07

It’s no error message and it’s also not the date that the user entered.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
James
  • 75
  • 7
  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). And yes, `DateTimeParseException` too, it’s from the same API. – Ole V.V. Feb 21 '21 at 09:33
  • Does this answer your question? [SimpleDateFormat giving wrong date instead of error](https://stackoverflow.com/questions/6028823/simpledateformat-giving-wrong-date-instead-of-error). I am immodest enough to recommend [my own answer here](https://stackoverflow.com/a/55021417/5772882). Sorry that I was too slow to close as a duplicate before others closed your question otherwise. – Ole V.V. Feb 21 '21 at 09:43

1 Answers1

2

Use modern date-time classes found in the java.time package. Never use Date, Calendar, and SimpleDateFormat.

Trap for DateTimeParseException

Parse your input string as a LocalDate object. Trap for DateTimeParseException in case of faulty input.

String input = "2021-99-99" ; 
try {
    LocalDate ld = LocalDate.parse( input ) ;
} catch ( DateTimeParseException e ) {
    … handle faulty input
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154