java實現將將時間段分成8段,判斷當前時間在哪一段時間裡?
阿新 • • 發佈:2019-02-17
用一個字串型別的陣列將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[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();
}
}
}