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
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!
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.
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 );
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 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 ) ;
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()