SimpleDateFormat.parse () - generates an invalid date for different date formats

Below is my code for parsing a date using SimpleDateFormat with a template:

String pattern = "yyyy-MM-dd"; SimpleDateFormat format = new SimpleDateFormat(pattern); try { Date date = format.parse("05-21-2030"); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); } 

You can see that the date I passed for parsing is different from the date format specified in SimpleDateFormat. In this case, I was expecting an excpetion, as the format is different, but it successfully dealt with some different date values. I got the result - Tue March 22 00:00:00 IST 12

When I transmit the same format as 2030-05-21 , it works fine.

Can you guys tell me how I can prevent such things in my code?

+6
source share
2 answers

Basically, you want SimpleDateFormat be strict, so set lenient to false.

 SimpleDateFormat format = new SimpleDateFormat(pattern); format.setLenient(false); 
+13
source

If you can afford to use the Java 8 time API, its formatter works as expected:

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); try { LocalDate date = LocalDate.parse("2030-05-21", formatter); System.out.println(date); LocalDate date2 = LocalDate.parse("05-21-2030", formatter); System.out.println(date2); } catch (DateTimeParseException e) { e.printStackTrace(); } 

Output:

 2030-05-21 java.time.format.DateTimeParseException: Text '05-21-2030' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1947) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1849) at java.time.LocalDate.parse(LocalDate.java:400) at java8.Snippet.main(Snippet.java:25) 
+3
source

Source: https://habr.com/ru/post/987248/


All Articles