我想检查目标时间是否在两个给定时间之间,而不考虑使用Java8时间的日期。假设开始时间21:30,结束时间06:30,目标时间03:00 ,所以程序应该返回true。
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."); } }推荐答案
你使用了LocalTime,它不存储日期信息,只存储时间。 然后你试图检查目标时间是否在开始时间之后( 03:00 21:30之后)。这个陈述是错误的。
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."); } }更多推荐
Java:如何检查给定时间是否介于两次之间?
发布评论