user1539343 user1539343 - 3 months ago 16
Java Question

SimpleDateFormat ambiguous matching

I have the code:

public List<Date> parse(String date) {
// todo: for parsing
List<Date> dateList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setLenient(true);
for (String format: DATE_FORMATS) {
sdf = new SimpleDateFormat(format);
try {
Date dt = sdf.parse(date);
System.out.println("Success! "+format);
dateList.add(dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
//System.err.println("failed!");
}
}
return dateList;
}


which is called:

parse("Monday Aug 29 5:51 PM GMT 2016")


I am getting the results:

Success! EEEE MMM dd hh:mm a z yyyy
Success! EEEE MMM yyyy hh:mm a z dd


Why does the second pattern match the example? Any enlightenment would be highly appreciated.

Thanks

Answer

your bellow code will overridden by new object creation.

sdf.setLenient(true);

object creation after modifying attribute.(useless above line due to bellow)

 sdf = new SimpleDateFormat(format);//replace this code by applyPattern

Now Lenient will again have default value.

instead of that use method like bellow to dynamically set pattern to sdf

sdf.applyPattern(arg0);
Comments