Java:如何检查给定时间是否介于两次之间? [英] Java: How to check whether given time lies between two times?

查看:198
本文介绍了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:如何检查给定时间是否介于两次之间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆