How to check whether a time is between particular range?

前端 未结 4 1035
温柔的废话
温柔的废话 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 06:54

    Joda Time is a pretty straightforward library to be used, and if you define the comparison date objects as LocalDate, then you can use the isBefore(), isAfter() boolean methods: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#isBefore-java.time.chrono.ChronoLocalDateTime- Hope it helps!

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-23 07:01

    java.time

    You are using old outmoded classes. They have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

    LocalTime

    The LocalTime class actually truly represents a time-of-day only value, unlike the old java.sql.Time and java.util.Date classes.

    LocalTime start = LocalTime.of( 8 , 0 );
    LocalTime stop = LocalTime.of( 15 , 0 );
    

    Time zone

    Determining the current time requires a time zone. For any given moment the time varies around the globe by time zone.

    ZoneId zoneId = ZoneId.of( "America/Montreal" );
    LocalTime now = LocalTime.now( zoneId );
    

    Compare

    Compare by calling equals, isAfter, or isBefore. We use the Half-open approach here as is common in date-time work where the beginning is inclusive while the ending is exclusive.

     Boolean isNowInRange = ( ! now.isBefore( start ) ) && now.isBefore( stop ) ;
    
    0 讨论(0)
  • 2021-01-23 07:12

    Using Date for the current time is fine. There's a few ways you can go about it.

    1. System.currentTimeInMillis()
    
    2. Date today = new Date()
    
    0 讨论(0)
提交回复
热议问题