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.");
}
}
in your scenario it seems that if startTime > endTime no matter what's targetTime you'll return true.
So update the if statement:
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
after21:30
). This statement is false.Your start time should be before end time.
If you need to handle night shift try following: