Java Date Check

I need to confirm user input as a valid date. User can enter dd / mm / yyyy or mm / yyyy (both valid)

to check it out i did

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
}

since the starting month of GregorianCalendar from 0, 30/01/2009 or 12/2009 gives an error.

any suggestion how to solve this problem.

+5
source share
2 answers

Use SimpleDateformat. If the parsing failed, he chose 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);
    }
}
+11
source

Use SimpleDateFormatto check Dateand setLenientto false.

+3
source

All Articles