Java日期验证 [英] Java Date validation
本文介绍了Java日期验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将用户输入验证为有效日期。用户可以输入dd / mm / yyyy或mm / yyyy(均为有效)
i need to validate user input as valid date. User can enter dd/mm/yyyy or mm/yyyy (both are valid)
验证我在做
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
}
如GregorianCalendar开始月份为0,30/01/2009或12/2009给出错误。
as GregorianCalendar start month with 0, 30/01/2009 or 12/2009 gives error.
任何建议如何解决这个问题。
any suggestion how to solve this issue.
推荐答案
使用 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);
}
}
这篇关于Java日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文