Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date validation

Tags:

java

date

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.

like image 937
sn s Avatar asked Sep 07 '11 10:09

sn s


2 Answers

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);
    }
}
like image 184
dacwe Avatar answered Oct 21 '22 02:10

dacwe


Use SimpleDateFormat to validate Date and setLenient to false.

like image 21
jmj Avatar answered Oct 21 '22 04:10

jmj