I was trying to block incompatible date in input. So I intentionally gave wrong date as string. I set calendar.setLenient
to false
hoping that it would not allow date to parse. But It pass through it. Below is my code:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws Exception{
try {
String from ="2018-15-18";
String to = "2018-15-18";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender1 = Calendar.getInstance();
Calendar calender2 = Calendar.getInstance();
calender1.setLenient(false);
calender2.setLenient(false);
calender1.setTime(sdf.parse(from));
calender2.setTime(sdf.parse(to));
Date dtFrom = calender1.getTime();
Date dtTo = calender2.getTime();
System.out.println(sdf.format(dtFrom));
if((from!=null && !from.isEmpty())&&(to!=null && !to.isEmpty())&&(dtFrom!=null && dtTo!=null))
System.out.println("ok");
else
System.out.println("not ok");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
As I have given wrong date i.e. month 15 does not exist. So I was expecting exception on line calender1.setTime(sdf.parse(from));
but it pass through and printing date value as : 2019-03-18
. I did not wanted that. Why is it so? How can I make sure wrong date input should not be entertained further in my code once it is not able to parse.