判斷某個時間在不在某個時間段
阿新 • • 發佈:2019-01-30
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; }