How to check whether a time is between particular range?

前端 未结 4 1036
温柔的废话
温柔的废话 2021-01-23 06:36

I need to check whether current time is between 8 AM and 3 PM or not. If it is between those time range, then I need to return yes otherwise return false.

boolea         


        
4条回答
  •  盖世英雄少女心
    2021-01-23 07:00

    If you're using a version of Java prior to Java 8, take a look at the API documentation for Joda.

    Specifically, there is an AbstractInterval#containsNow() method which will allow you to do what you want.

    For example:

    new Interval(start, end).containsNow();
    

    where start and end can either be any of a number of different values/objects. See the documentation for the different constructors available: Interval


    You could modify your method to be like so:

    boolean isNowBetweenDateTime(final DateTime s, final DateTime e) {
        return new Interval(s, e).containsNow();
    }
    

    That said, it's only one line, so you really shouldn't need to wrap it with your own method :)

    Again, take a look at the documentation. The Interval constructor can take a variety of objects/values, so pick whichever suits your needs. I recommend DateTime since it seems to best describe what you're looking to do.

提交回复
热议问题