一、先说一下年月日(yyyy-MM-dd)正则表达式:
1.年月日正则表达式:
^((19|20)[0-9]{2})-((0?2-((0?[1-9])|([1-2][0-9])))|(0?(1|3|5|7|8|10|12)-((0?[1-9])|([1-2][0-9])|(3[0-1])))|(0?(4|6|9|11)-((0?[1-9])|([1-2][0-9])|30)))$
或者这样,2月中的9可以变化
^((19|20)[0-9]{2})-((0?2-((0?[1-9])|(1[0-9]|2[0-9])))|(0?(1|3|5|7|8|10|12)-((0?[1-9])|([1-2][0-9])|(3[0-1])))|(0?(4|6|9|11)-((0?[1-9])|([1-2][0-9])|30)))$
下面就是JAVA判断年月日格式是否正确的两种方法(这两种方法实现类似)
第一种:先正则判断,后判断月份是否2月(再者就是闰年判断),返回Map
/**
* 判断日期
* @param date
* @return
*/
public static Map<String,Object> dateIsPass(String date) {
Map<String,Object> rsMap = new HashMap<String,Object>();
rsMap.put("format", false);
rsMap.put("msg", "日期格式不对。");
//年月日的正则表达式,此次没有理会2月份闰年
String regex = "^((19|20)[0-9]{2})-((0?2-((0?[1-9])|([1-2][0-9])))|(0?(1|3|5|7|8|10|12)-((0?[1-9])|([1-2][0-9])|(3[0-1])))|(0?(4|6|9|11)-((0?[1-9])|([1-2][0-9])|30)))$";
//开始判断,且符合正则表达式
if(date.matches(regex)) {
rsMap.put("format", true);
rsMap.put("msg", "日期格式正确。");
//分割截取0年份1月份2日
String[] dateSplit = date.split("-");
//判断输入的月份是否是二月,输入的是二月的话,还需要判断该年是否是闰年
if("02".equals(dateSplit[1]) || "2".equals(dateSplit[1])) {
int year = Integer.parseInt(dateSplit[0]);
// 不是闰年,需要判断日是否大于28
if (!(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)) {
int day = Integer.parseInt(dateSplit[2]);
if(day > 28) {
rsMap.put("format", false);
rsMap.put("msg", year+"年2月不是闰年,只有28天!");
}
}
}
}
return rsMap;
}
第二种:先判断月份是否2月(再者就是闰年判断),后拼凑正则表达式,返回boolean
/**
* 判断日期
* @param date
* @return
*/
public static boolean dateIsPass2(String date) {
boolean flag = false;
int d = 8;
//分割截取0年份1月份2日
String[] dateSplit = date.split("-");
//判断输入的月份是否是二月,输入的是二月的话,还需要判断该年是否是闰年
if("02".equals(dateSplit[1]) || "2".equals(dateSplit[1])) {
int year = Integer.parseInt(dateSplit[0]);
// 不是闰年,需要判断日是否大于28
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
d = 9;
}
}
//年月日的正则表达式,此次没有理会2月份闰年
String regex = "^((19|20)[0-9]{2})-((0?2-((0?[1-9])|(1[0-9]|2[0-"+d+"])))|(0?(1|3|5|7|8|10|12)-((0?[1-9])|([1-2][0-9])|(3[0-1])))|(0?(4|6|9|11)-((0?[1-9])|([1-2][0-9])|30)";
//开始判断,且符合正则表达式
if(date.matches(regex)) {
flag = true;
}
return flag;
}