使用正则表达式判断
使用正则表达式判断String类型的字符串是否为时间格式yyyy-MM-dd HH:mm:ss
public static boolean valiDateTime(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;
}
如果判断的只有年月日,即把format换成
String format = “((19|20)[0-9]{2})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])”;
获取当月的第一天
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH)
获取当月的最后一天
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH)