-1

I'm having an invalid date: with month > 12.

String input = "12-30-2017"; 
DateFormat inputFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = inputFormatter.parse(input);

while I have my debug cursor at the date , it gives me 12-06-2019. It seems it is adding the months and making a valid date.

I need to throw invalid date here. how to do that.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jabongg
  • 2,099
  • 2
  • 15
  • 32
  • 5
    https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#setLenient-boolean-. But you'd better forget aboud Date and DateFormat, which are obsolete, and use the java.time API. – JB Nizet Sep 02 '17 at 12:19
  • Try `inputFormatter.setLenient(false)` before parsing to enforce strict parsing. – Kevin Anderson Sep 02 '17 at 12:34
  • 3
    Why do you think a date with format MM-dd-yyyy would be correctly parsed with a format yyyy-MM-dd? – Mark Rotteveel Sep 02 '17 at 12:38
  • @MarkRotteveel, the question states “I need to throw invalid date here.” I don’t take that to mean that a correct parsing was expected. :-) – Ole V.V. Sep 02 '17 at 14:40
  • @JBNizet already said to use [the modern date & time API](https://docs.oracle.com/javase/tutorial/datetime/index.html). One advantage is it behaves like you expect: `LocalDate date = LocalDate.parse("12-30-2017", DateTimeFormatter.ofPattern("yyyy-MM-dd"));` gives `java.time.format.DateTimeParseException: Text '12-30-2017' could not be parsed at index 0` – Ole V.V. Sep 02 '17 at 14:48

2 Answers2

2

Please Try inputFormatter.setLenient(false);

A_J
  • 977
  • 4
  • 16
  • 44
1

Your formatting pattern must match your input string.

Use modern java.time classes rather than the troublesome legacy date-time classes.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
LocalDate ld = LocalDate.parse( "12-30-2017" , f ) ;

Whenever possible, use standard ISO 8601 formats for exchanging date-time strings.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154