tl;dr
LocalTime now = LocalTime.now( ZoneId.of( "America/Montreal" ) );
Boolean isNowWithinRange =
(
( ! now.isBefore( LocalTime.parse( "11:00:00" ) ) )
&& now.isBefore( LocalTime.parse( "12:00:00" )
) ;
Details
The accepted answer is a good attempt but has multiple flaws.
Bad practice to call now
twice, as you end up making invalid comparisons with two different moments. Call once, and assign to a variable.
Do not ignore the crucial issue of time zone. Better to explicitly pass the optional time zone argument to now( ZoneId )
than rely implicitly on the JVM’s current default which can change at any moment.
You can ask for the device’s current default time zone. But if vital, you should ask/confirm with the user.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalTime now = LocalTime.now( z );
You can parse the input strings directly as LocalTime
objects.
LocalTime start = LocalTime.parse( "11:00:00" );
LocalTime stop = LocalTime.parse( "12:00:00" );
Common practice in date-time work is to use the Half-Open approach for spans of time. The beginning is inclusive while the ending is exclusive. Using this approach consistently makes your code more understandable and less error-prone.
Tip: Saying “not before start” is a briefer way of saying “is equal to or later than start”.
Boolean isNowWithinRange = ( ( ! now.isBefore( start ) ) && now.isBefore( stop ) ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.