Java: How to check whether given time lies between

2019-06-10 10:35发布

I want to check whether target time lies between two given times without considering date using Java8 time. Let say if starting time is "21:30" , ending time is "06:30" and target time is "03:00", so program should return true.

    @Test
    public void posteNuit()
    {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");

        String s = "21:30";
        String e = "06:30";

        String t = "03:00";

        LocalTime startTime = LocalTime.parse(s, format);
        LocalTime endTime = LocalTime.parse(e, format);
        LocalTime targetTime = LocalTime.parse(t, format);

        if ( targetTime.isBefore(endTime) && targetTime.isAfter(startTime) ) {
            System.out.println("Yes! night shift.");
        } else {
            System.out.println("Not! night shift.");
        }
    }

2条回答
三岁会撩人
2楼-- · 2019-06-10 10:50

in your scenario it seems that if startTime > endTime no matter what's targetTime you'll return true.

So update the if statement:

if (( startTime.isAfter(endTime) && targetTime.isBefore(startTime)
        && targetTime.isAfter(endTime)  )
     || ( startTime.isBefore(endTime) && targetTime.isBefore(endTime) 
        && targetTime.isAfter(startTime) )) {
查看更多
Deceive 欺骗
3楼-- · 2019-06-10 10:56

You've used LocalTime which doesn't store date information, only time. Then you are trying to check if target time is after start time (03:00 after 21:30). This statement is false.

Your start time should be before end time.

If you need to handle night shift try following:

    if (startTime.isAfter(endTime)) {
        if (targetTime.isBefore(endTime) || targetTime.isAfter(startTime)) {
            System.out.println("Yes! night shift.");
        } else {
            System.out.println("Not! night shift.");
        }
    } else {
        if (targetTime.isBefore(endTime) && targetTime.isAfter(startTime)) {
            System.out.println("Yes! without night shift.");
        } else {
            System.out.println("Not! without night shift.");
        }
    }
查看更多
登录 后发表回答