- 正则表达式
// 时间格式 static String dateFormat = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"; // 平年年月日 static String noLeapYearDate = "^(((2\\d{3})-(0[13578]|1[02])-(0[1-9]|1[0-9]|2[0-9]|3[01]))|" + "((2\\d{3})-(0[469]|11)-(0[1-9]|1[0-9]|2[0-9]|30))|" + "((2\\d{3})-(02)-(0[1-9]|1[0-9]|2[0-8])))"; // 闰年年月日 static String leapYearDate = "^(((2\\d{3})-(0[13578]|1[02])-(0[1-9]|1[0-9]|2[0-9]|3[01]))|" + "((2\\d{3})-(0[469]|11)-(0[1-9]|1[0-9]|2[0-9]|30))|" + "((2\\d{3})-(02)-(0[1-9]|1[0-9]|2[0-9])))"; // 时分秒 static String hourMinSecondFormat = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])";
- 校验方法
private static boolean checkDate(String strDate) { // 非空校验 if (null == strDate || "".equals(strDate)) { return false; } // 长度校验 if (strDate.trim().length() != 19) { return false; } // 格式校验 if (!checkDateFormat(strDate)) { return false; } // 值校验 if (!checkDateData(strDate)) { return false; } return true; } private static boolean checkDateFormat(String strDate) { Pattern pattern = Pattern.compile(dateFormat); if(pattern.matcher(strDate).matches()){ return true; } return false; } private static boolean checkDateData(String strDate) { String year = strDate.substring(0, 4); String yearMonthDay = strDate.substring(0, 10); String HourMinSecond = strDate.substring(11, 19); // 校验年月日 if (!checkYearMonthDay(yearMonthDay, Integer.parseInt(year))) { return false; } // 校验时分秒 if (!checkHourMinSecond(HourMinSecond)) { return false; } // 时间时效校验 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; Date currentDate = new Date(); try { date = formatter.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } if (currentDate.before(date)) { return false; } return true; } private static boolean checkYearMonthDay(String date, int year) { Pattern noLeapPattern = Pattern.compile(noLeapYearDate); Pattern leapYearPattern = Pattern.compile(leapYearDate); if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){ if(!leapYearPattern.matcher(date).matches()){ return false; } }else { if(!noLeapPattern.matcher(date).matches()){ return false; } } return true; } private static boolean checkHourMinSecond(String date) { Pattern timePattern = Pattern.compile(hourMinSecondFormat); if(timePattern.matcher(date).matches()){ return true; } return false; }
- 校验测试代码与结果
public static void main(String[] args) { String date1 = "2020-01-31 23:17:00"; String date2 = "2019-02-28 19:10:00"; String date3 = "2019-02-29 19:10:00"; // DateTools类名 System.out.println("date1 : "+DateTools.checkDate(date1)); System.out.println("date2 : "+DateTools.checkDate(date2)); System.out.println("date3 : "+DateTools.checkDate(date3)); }
字符串“yyyy-MM-dd HH:mm:ss“的时间格式、值的校验
最新推荐文章于 2023-09-08 14:54:00 发布