校验日期格式{YYYY-MM-DD的 java代码
1. yyyy-MM-dd 格式校验
1 public class RegexpUtils { 2 3 /** 4 * 是否是 yyyy-MM-dd 日期格式 校验 5 * @param date 日期 6 * @return boolean 7 */ 8 public static boolean isDateFormat(String date) { 9 if (StringUtils.isBlank(date)) { 10 return false; 11 } 12 String regexp = "[0-9]{4}-[0-9]{2}-[0-9]{2}"; 13 return Pattern.compile(regexp).matcher(date).matches(); 14 } 15 16 }
2. yyyy-MM-dd hh:mm:ss 格式校验
1 import java.util.regex.Matcher; 2 import java.util.regex.Pattern; 3 4 public class TimeUtil { 5 /** 6 * 验证时间字符串格式输入是否正确 7 * @param timeStr 8 * @return 9 */ 10 public static boolean valiDateTimeWithLongFormat(String timeStr) { 11 String format = "((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) " 12 + "([01]?[0-9]|2[0-3]):[0-5]?[0-9]:[0-5]?[0-9]"; 13 Pattern pattern = Pattern.compile(format); 14 Matcher matcher = pattern.matcher(timeStr); 15 if (matcher.matches()) { 16 pattern = Pattern.compile("(\\d{4})-(\\d+)-(\\d+).*"); 17 matcher = pattern.matcher(timeStr); 18 if (matcher.matches()) { 19 int y = Integer.valueOf(matcher.group(1)); 20 int m = Integer.valueOf(matcher.group(2)); 21 int d = Integer.valueOf(matcher.group(3)); 22 if (d > 28) { 23 Calendar c = Calendar.getInstance(); 24 c.set(y, m-1, 1); 25 int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); 26 return (lastDay >= d); 27 } 28 } 29 return true; 30 } 31 return false; 32 } 33 34 public static void main(String[] args){ 35 System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-5-2 08:02:02")); 36 System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-02-29 08:02:02")); 37 System.out.println(TimeUtil.valiDateTimeWithLongFormat("2015-02-29 08:02:02")); 38 System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-02-02 082:02")); 39 } 40 }