How to check whether a time is between particular range?

前端 未结 4 1083
温柔的废话
温柔的废话 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条回答
  •  猫巷女王i
    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 ) ;
    

提交回复
热议问题