Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat.parse() - generates wrong date for different date-formats

Tags:

java

date

Below is my code to parse the date using SimpleDateFormat with pattern:

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 the date which I passed to parse is different from date format which is specified in SimpleDateFormat. In this case I was expecting kind of excpetion as format is different but it parsed successfully with some different date values. I got the output - Tue Mar 22 00:00:00 IST 12

When I pass the same format like 2030-05-21 it works fine.

Can you guys please let me know how can I prevent such things in my code?

like image 600
Bhavesh Shah Avatar asked May 15 '15 06:05

Bhavesh Shah


1 Answers

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

SimpleDateFormat format = new SimpleDateFormat(pattern);
format.setLenient(false);
like image 151
dogant Avatar answered Oct 29 '22 16:10

dogant