天天看點

Java 判斷當天某個時間是否在某個時間内

某些活動 需要判斷  目前時間 是否處于規定的時間段,時間段: openWeek[]{1,5}, openTimes[]{"18:00:00-19:00:00","18:00:00-19:00:00"} 可能多個。

public class Demo9_timeValid {
    
    // openTime = "18:00:00-19:00:00"
    public boolean timeValid(Calendar currentTime, String openTimes) {
        LocalDateTime localTime = LocalDateTime.of(currentTime.get(Calendar.YEAR), currentTime.get(Calendar.MONTH) + 1,
                currentTime.get(Calendar.DAY_OF_MONTH), currentTime.get(Calendar.HOUR_OF_DAY),
                currentTime.get(Calendar.MINUTE), currentTime.get(Calendar.SECOND));
        String[] timeStr = openTimes.split("-");
        LocalDateTime t1 = LocalDateTime.of(LocalDate.now(), LocalTime.parse(timeStr[0]));
        LocalDateTime t2 = LocalDateTime.of(LocalDate.now(), LocalTime.parse(timeStr[1]));
        if (localTime.compareTo(t1) >= 0 && localTime.compareTo(t2) < 1)
            return true;
        return false;
    }
    
    public static void main(String[] args){

        Demo9_timeValid valid = new Demo9_timeValid();
        boolean flag = false;
        // 1 對應周一 對應 opentimes[0] 的第一個
        int[] tempWeeks = {1,4};
        String[] openTimes = {"18:00:00-19:00:00","20:00:00-21:00:00"};
        int week = LocalDate.now().getDayOfWeek().getValue();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        for (int i = 0; i < tempWeeks.length ; i++) {
            if(week == tempWeeks[i]){
                flag = valid.timeValid(calendar,openTimes[i]);
                if(flag)
                    System.out.println(flag);
            }
        }
    }

}
           

繼續閱讀