两种方式 :
一种是验证时间内,一种是用正则来校验
/**
* 判断时间是否在某个时间段内
*
* @param nowTime 验证的时间
* @param beginTime 最早时间
* @param endTime 最晚时间
* @return
*/
public static boolean belongCalendar(String nowT, String beginT, String endT) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date nowTime = null;
Date beginTime = null;
Date endTime = null;
try {
nowTime = sdf.parse(nowT);
beginTime = sdf.parse(beginT);
endTime = sdf.parse(endT);
} catch (ParseException e) {
}
Calendar date = Calendar.getInstance();
date.setTime(nowTime);
Calendar begin = Calendar.getInstance();
begin.setTime(beginTime);
Calendar end = Calendar.getInstance();
end.setTime(endTime);
if (date.after(begin) && date.before(end)) {
return true;
} else if (nowTime.compareTo(beginTime) == 0 || nowTime.compareTo(endTime) == 0) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.println(belongCalendar("2001-05-27 00:00:00","2000-01-01 00:00:00","2021-05-27 00:00:00"));//true
System.out.println(belongCalendar("1999-05-27 00:00:00","2000-01-01 00:00:00","2021-05-27 00:00:00"));//false
}
/**
* java 正则验证时间的有效性 年月日 时分秒
* @param timeStr 例:2000-08-03 00:00:00
* @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(valiDateTimeWithLongFormat("2001-05-27 00:00:00"));//true
System.out.println(valiDateTimeWithLongFormat("2001-05-27"));//false
}