用一个字符串类型的数组将8段存入其中,然后循环比较。比较的时候要将字条串用split(“-”)先分割开,再分别转为Date类型。假如d1是起始时间,d2是结束时间,当前时间是d3,d3.after(d1)为true,d3.before(d2)为true时,当前时间就是这一节中,循环变量i+1是第几段。
String[] dates = new String[8];
dates[0] = "06:00-08:59";
dates[1] = "09:00-10:59";
dates[2] = "11:00-13:59";dates[3] = "14:00-16:59";
dates[4] = "17:00-19:59";dates[5] = "20:00-21:59";
dates[6] = "22:00-23:59";dates[7] = "01:00-06:00";
for (int i = 0; i < dates.length; i++) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String currentDate = sdf.format(new Date());
String dateStr = dates[i];
String[] dateArr = dateStr.split("-");
try {
Date currDate = sdf.parse(currentDate);//当前时间
Date startDate = sdf.parse(dateArr[0]);//每节开始时间
Date endDate = sdf.parse(dateArr[1]);//每节结束时间
if(currDate.after(startDate) && currDate.before(endDate)){
System.out.println("当前时间属于第"+(i+1)+"节");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}