I have a java code, that inputs date in a specific format.
static Date parseDate(String userInput){
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(userInput);
System.out.println(date);
}catch(ParseException pe){
date=null;
System.out.println("Not a valid date");
}
return date;
}
Now I'm entering 2015-13-11 89:90:90
which is an invalid date. But it returns Thu Jan 14 18:31:30 IST 2016
as the date. Why is this so? How do I make it to return null as the date?
From a glance of the javadocs, it seems to be using a lenient
mode of parsing in which it accepts poorly formatted input:
Adding this line
format.setLenient(false);
after the initialization of your DateFormat object appears to fix it.
I will attempt to explain why this is happening.
The date is different because the values which exceed their fields' maximum are rolled up into the next greater field.
I am not sure the order in which it is resolved, but here is what happens in general:
Given 2015-13-11 89:90:90
This leaves us with 2016-01-14 18:31:30.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With