我需要验证用户输入为有效日期.用户可以输入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)