一、先说一下年月日(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
1 /** 2 * 判断日期 3 * @param date 4 * @return 5 */ 6 public static Map<String,Object> dateIsPass(String date) { 7 Map<String,Object> rsMap = new HashMap<String,Object>(); 8 rsMap.put("format", false); 9 rsMap.put("msg", "日期格式不对。"); 10 //年月日的正则表达式,此次没有理会2月份闰年 11 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)))$"; 12 //开始判断,且符合正则表达式 13 if(date.matches(regex)) { 14 rsMap.put("format", true); 15 rsMap.put("msg", "日期格式正确。"); 16 //分割截取0年份1月份2日 17 String[] dateSplit = date.split("-"); 18 //判断输入的月份是否是二月,输入的是二月的话,还需要判断该年是否是闰年 19 if("02".equals(dateSplit[1]) || "2".equals(dateSplit[1])) { 20 int year = Integer.parseInt(dateSplit[0]); 21 // 不是闰年,需要判断日是否大于28 22 if (!(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)) { 23 int day = Integer.parseInt(dateSplit[2]); 24 if(day > 28) { 25 rsMap.put("format", false); 26 rsMap.put("msg", year+"年2月不是闰年,只有28天!"); 27 } 28 } 29 } 30 } 31 return rsMap; 32 }
第二种:先判断月份是否2月(再者就是闰年判断),后拼凑正则表达式,返回boolean
1 /** 2 * 判断日期 3 * @param date 4 * @return 5 */ 6 public static boolean dateIsPass2(String date) { 7 boolean flag = false; 8 int d = 8; 9 //分割截取0年份1月份2日 10 String[] dateSplit = date.split("-"); 11 //判断输入的月份是否是二月,输入的是二月的话,还需要判断该年是否是闰年 12 if("02".equals(dateSplit[1]) || "2".equals(dateSplit[1])) { 13 int year = Integer.parseInt(dateSplit[0]); 14 // 不是闰年,需要判断日是否大于28 15 if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { 16 d = 9; 17 } 18 } 19 //年月日的正则表达式,此次没有理会2月份闰年 20 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)"; 21 //开始判断,且符合正则表达式 22 if(date.matches(regex)) { 23 flag = true; 24 } 25 return flag; 26 }