isBetween方法调用isBetweenL方法,中间处理了一下时长
isBetweenL方法,主要任务是构造开始时间的字符串和结束时间的字符串,接着使用date类实例的compareTo方法与当前时间做比较,完成功能
0为当天0点。24为明天0点。
private boolean isBetween(int startHour, int endHour) {
boolean result = false;
int length;
if (startHour > endHour) {
length = 24 - (startHour -endHour );
}else {
length = endHour - startHour;
}
System.out.println("length : "+length);
try {
result = isBetweenL(startHour, length);//调用时长的方法
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
private boolean isBetweenL(int startHour, int timeLong) throws ParseException {
if (startHour<0){
return false;
}
if (timeLong<1){
return false;
}
String startTime;
String endTime;
Calendar calendar = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String today = dateFormat.format(date);
if (startHour < 0) {//开始时间小于零设置为0
startHour = 0;
}
timeLong = timeLong % 24;//时长超过24小时取余
int end = (startHour + timeLong) % 24;//结束时间,超过24时取余
startTime = today + " " + buildHour(startHour) + ":00:00";
if (startHour < end) {//在同一天
endTime = today + " " + buildHour(end) + ":00:00";
} else {//不在同一天
calendar.add(Calendar.HOUR_OF_DAY, timeLong);
String nextDay = dateFormat.format(calendar.getTime());
endTime = nextDay + " " + buildHour(end) + ":00:00";
}
DateFormat dateF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("isBetween: start " + startTime + " " + dateF.parse(startTime));
System.out.println("isBetween: end " + endTime + " " + dateF.parse(endTime));
System.out.println("isBetween: date " + date);
System.out.println("isBetween: start - cur " + dateF.parse(startTime).compareTo(date));
System.out.println("isBetween: cur - end " + date.compareTo(dateF.parse(endTime)));
return dateF.parse(startTime).compareTo(date) == date.compareTo(dateF.parse(endTime));
}
private String buildHour(int hour) {
String temp;
if (hour > 9) {
temp = String.valueOf(hour);
} else {
temp = "0" + hour;
}
return temp;
}