String::split
Generally, for splitting strings into parts, use the String::split
command. See the Question How to split a string in Java for much discussion.
String[] parts = "07:11".split( ":" );
Arrays.toString( parts ): [07, 11]
But I do not recommend this approach in your case. Read on.
LocalTime
Java offers a purpose-built class for you: LocalTime
. This class represents a time-of-day without a date and without a time zone. The clock is a single generic 24-hour day that ignores anomalies such as Daylight Saving Time (DST).
Your input such as 07:11
happens to comply with the standard ISO 8601 formats. The java.time classes use these formats by default when parsing or generating strings representing date-time values. So no need to specify a formatting pattern.
LocalTime localTime = LocalTime.parse( "07:11" );
From there you may interrogate for the hour portion or the minute portion.
int hourOfDay = localTime.getHour();
int minuteOfHour = localTime.getMinute();
But your real goal is to compare the time to see if it is between 5 AM and 10 PM. For example, is this true: 5 AM < 07:11 < 10 PM
. So no need to tear apart the time into pieces. Instead, make your comparison more directly, and in a more self-documenting way, using the LocalTime
class.
LocalTime start = LocalTime.of( 5 , 0 ); // 5 AM = 05:00.
LocalTime stop = LocalTime.of( 22 , 0 ); // 10 PM = 22:00.
Boolean isBetween =
( ! localTime.isBefore( start ) )
&&
localTime.isBefore( stop )
;
See this code run live at IdeOne.com.
About that comparison statement:
- The first part asks “Is our target either exactly on the start or after the start?”. A shorter way to ask that is, “Is our target not before the start?”. If “not before” then logically it must either be exactly on or after.
- The second part asks if our target is before the stop rather than “is equal to or before”. This means we are using the Half-Open approach to defining a span of time. In Half-Open, the beginning is inclusive while the ending is exclusive. This is commonly used in date-time work. I believe using it consistently throughout your code base and business logic removes much of the confusion and ambiguity that arises from spans of time.