0

I have a string format date with "dd/MM/yyyy" (pattern Brazil)

But in my code when convert in date, accept a wrong months.

    *String str = "01/15/2021"; 
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date dt = df.parse(str);        
    System.out.println(dt);*

The result is: Tue Mar 01 00:00:00 BRT 2022

How invalidate this ?

Anderson
  • 87
  • 1
  • 7
  • `df.setLenient(valse);` – g00se Aug 02 '21 at 22:05
  • 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/). – Ole V.V. Aug 03 '21 at 00:28

2 Answers2

1

This should fix it:

df.setLenient(false);

But please look at other date types like LocalDate or ZonedDate. Much easier down the road ;)

grekier
  • 2,322
  • 1
  • 16
  • 23
1

Modern solution uses java.time classes, never Date or Calendar.

By default, LocalDate parsing is strict rather than lenient. Trap for DateTimeParseException.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String input = "01/15/2021" ;
try {
    LocalDate ld = LocalDate.parse( input , f ) ;
} catch ( DateTimeParseException e ) {
    … handle faulty input here …
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • `DateTimeFormatter.ofPattern()` gives us a formatter with smart resolver style. So the code will still accept for instance `31/02/2021` (and interpret it as 2021-02-28). For better validation use `DateTimeFormatter.ofPattern( "dd/MM/uuuu" ).withResolverStyle( ResolverStyle.STRICT )`. – Ole V.V. Aug 03 '21 at 00:51