See if the current time falls within a specific range of time in the current day in Java

前端 未结 6 879
天命终不由人
天命终不由人 2020-12-10 13:52

I am sure this was done 1000 times in 1000 different places. The question is I want to know if there is a better/standard/faster way to check if current \"time\" is between

6条回答
  •  萌比男神i
    2020-12-10 14:59

    The Midnight Problem

    Other answers fail to mention it - and the OP doesn't ask - but you should really consider when the interval spans across midnight.

    Time is difficult. I purposely left the "long" version of the code and didn't abbreviate logical conditions to make it as clear as possible the what's and the why's.

    /**
     * Takes into consideration that the interval may span accross midnight
     *
     * @param clock to make unit testing easier, just replace for Clock.systemUTC() in your code 
     * @param start the interval start
     * @param end the interval end
     * @return true if "now" is inside the specified interval
     */
    static boolean isNowBetweenLocalTime(Clock clock, final LocalTime start, final LocalTime end) {
        LocalTime now = LocalTime.now(clock);
    
        // if interval crosses midnight
        if (end.isBefore(start)) {
            if (now.isAfter(start) && now.isAfter(end)) {
                return true;
            }
            if (now.isBefore(start) && now.isBefore(end)) {
                return true;
            }
            return false;
        }
    
        // if interval does not cross midnight
        if (end.isAfter(start)) {
            if (now.isAfter(start) && now.isBefore(end)) {
                return true;
            }
            return false;
        }
    
        return false; // interval is 0 so start and end always outside interval
    }
    

    Verbosity is not always wrong. This method will be buried in a utility class and two years from now you'll thank yourself for understanding what it does!

提交回复
热议问题