版权声明
1. 本站文章和资源均来自互联网收集和整理,本站不承担任何责任及版权问题。
2. 相关版权归作者及其公司所有,仅供学习研究用途,请勿用于商业目的。
3. 若侵犯您的版权,请发邮件至webmaster@ishare1.cn联系我们,我们确认后将立即删除。

1、使用正则判断是否日期(推荐:java视频教程)
public boolean isDate(String date) {
/**
* 判断日期格式和范围
*/
String rexp = "^((d{2}(([02468][048])|([13579][26]))[-/s]?((((0?[13578])|(1[02]))[-/s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[-/s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[-/s]?((0?[1-9])|([1-2][0-9])))))|(d{2}(([02468][1235679])|([13579][01345789]))[-/s]?((((0?[13578])|(1[02]))[-/s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[-/s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[-/s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
Pattern pat = Pattern.compile(rexp);
Matcher mat = pat.matcher(date);
boolean dateType = mat.matches();
return dateType;
}
2、使用SimpleDateFormat类设置日期格式,然后通过抛出异常来判断
public boolean isValidDate(String str) {
boolean convertSuccess = true;
// 指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
//如果想判断格式为yyyy-MM-dd,需要写成-分隔符的形式
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// 如果抛出ParseException或者NullPointerException,就说明格式不对
convertSuccess = false;
}
return convertSuccess;
}
更多java知识请关注java基础教程栏目。
爱分享




