验证每个月的最大天数如下:
1 |
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH); |
使用Java正则表达式匹配一个时间格式的字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import java.util.regex.Matcher; import java.util.regex.Pattern; public class TimeUtil { /** * 验证时间字符串格式输入是否正确 * @param timeStr * @return */ public static boolean valiDateTimeWithLongFormat(String timeStr) { String format = "((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01]) " + "([01]?[0-9]|2[0-3]):[0-5]?[0-9]:[0-5]?[0-9]"; Pattern pattern = Pattern.compile(format); Matcher matcher = pattern.matcher(timeStr); if (matcher.matches()) { pattern = Pattern.compile("(\\d{4})-(\\d+)-(\\d+).*"); matcher = pattern.matcher(timeStr); if (matcher.matches()) { int y = Integer.valueOf(matcher.group(1)); int m = Integer.valueOf(matcher.group(2)); int d = Integer.valueOf(matcher.group(3)); if (d > 28) { Calendar c = Calendar.getInstance(); c.set(y, m-1, 1); int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); return (lastDay >= d); } } return true; } return false; } public static void main(String[] args){ System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-5-2 08:02:02")); System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-02-29 08:02:02")); System.out.println(TimeUtil.valiDateTimeWithLongFormat("2015-02-29 08:02:02")); System.out.println(TimeUtil.valiDateTimeWithLongFormat("2016-02-02 082:02")); } } |
输出
1 2 3 4 |
true true false false |
亲自试一试:Demo