Incorrect date parsing with SimpleDateFormat, Java

I need to parse the date from the input line using the date template "yyyy-MM-dd", and if the date appears in any other format, make an error.

This is my piece of code where I parse the date:

private void validateDate() throws MyException { Date parsedDate; String DATE_FORMAT = "yyyy-MM-dd"; try{ parsedDate = new SimpleDateFormat(DATE_FORMAT).parse(getMyDate()); System.out.println(parsedDate); } catch (ParseException e) { throw new MyException("Error occurred while processing date:" + getMyDate()); } } 

When I have a line like "2011-06-12" as an input to myDate, I get the output "Thu Sep 29 00:00:00 EEST 2011", which is good.

When I sent the wrong string like "2011-0612", I get the error as expected.

The problems begin when Im trying to pass a string that still has two dashes, but the number of digits is incorrect. Example:

input line "2011-06-1211" the result is "Tue Sep 23 00:00:00 EEST 2014".

input line "2011-1106-12" the result is "Mon 12 Feb 00:00:00 EET 2103".

I cannot change the input format of a string date.

How can i avoid this?

+6
source share
1 answer

Have you tried calling setLenient(false) on your SimpleDateFormat ?

 import java.util.*; import java.text.*; public class Test { public static void main(String[] args) throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); format.setLenient(false); Date date = format.parse("2011-06-1211"); // Throws... System.out.println(date); } } 

Please note that I also suggest setting the time zone and locale of your SimpleDateFormat . (Alternatively use Joda Time instead)

+9
source

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


All Articles