Java日期验证

sn *_*n s 6 java date

我需要验证用户输入为有效日期.用户可以输入dd/mm/yyyy或mm/yyyy(两者都有效)

验证我正在做的事情

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
}
Run Code Online (Sandbox Code Playgroud)

作为GregorianCalendar开始月份0,03/01/2009或12/2009给出错误.

任何建议如何解决这个问题.

dac*_*cwe 11

使用SimpleDateformat.如果解析失败则会抛出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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我同意你应该使用SimpleDateFormat,但你的例子是不完整的:如果没有在SimpleDateFormat上调用'setLenient(false)',它将接受无效输入并将其转换为无意义的日期.此外,在尝试第二种格式之前,您需要捕获第一个parse()抛出的异常. (2认同)