I have a REST api which involving date conversions. For that it has inputs like a dateString
and its format
.But my problem is I can't validate the date for some negative scenarios. For example
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("29-09-2014 20:35:27");
I expect the above code will throw exception, but it doesn't. So my validation fails. Can anyone suggest a solution
You need to tell the DateFormat
to parse strictly, instead of leniently (the default):
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setLenient(false);
sdf.parse("29-09-2014 20:35:27"); // Throws ParseException
See more on this question at Stackoverflow