i need to validate user input as valid date. User can enter dd/mm/yyyy or mm/yyyy (both are valid)
to validate this i was doing
try{
GregorianCalendar cal = new GregorianCalendar();
cal.setLenient(false);
String []userDate = uDate.split("/");
if(userDate.length == 3){
cal.set(Calendar.YEAR, Integer.parseInt(userDate[2]));
cal.set(Calendar.MONTH, Integer.parseInt(userDate[1]));
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(userDate[0]));
cal.getTime();
}else if(userDate.length == 2){
cal.set(Calendar.YEAR, Integer.parseInt(userDate[1]));
cal.set(Calendar.MONTH, Integer.parseInt(userDate[0]));
cal.getTime();
}else{
// invalid date
}
}catch(Exception e){
//Invalid date
}
as GregorianCalendar start month with 0, 30/01/2009 or 12/2009 gives error.
any suggestion how to solve this issue.
Use SimpleDateformat
. If the parsing failes it throws a ParseException
:
private Date getDate(String text) throws java.text.ParseException {
try {
// try the day format first
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
return df.parse(text);
} catch (ParseException e) {
// fall back on the month format
SimpleDateFormat df = new SimpleDateFormat("MM/yyyy");
df.setLenient(false);
return df.parse(text);
}
}
Use SimpleDateFormat
to validate Date
and setLenient
to false
.
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