Java:如何检查给定时间是否介于两次之间?

编程入门 行业动态 更新时间:2024-10-28 04:16:21
本文介绍了Java:如何检查给定时间是否介于两次之间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想检查目标时间是否在两个给定时间之间,而不考虑使用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:如何检查给定时间是否介于两次之间?

本文发布于:2023-10-27 03:52:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1532229.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   时间   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!