20:11:13 < 01:00:00 < 14:49:00
LocalTime target = LocalTime.parse( "01:00:00" ) ;
Boolean targetInZone = (
target.isAfter( LocalTime.parse( "20:11:13" ) )
&&
target.isBefore( LocalTime.parse( "14:49:00" ) )
) ;
java.time.LocalTime
The java.time classes include LocalTime
to represent a time-of-day only without a date and without a time zone.
So what I want is, 20:11:13 < 01:00:00 < 14:49:00.
First we define the boundaries. Your input strings happen to comply with standard ISO 8601 formats. The java.time classes use ISO 8601 formats by default, so no need to specify a formatting pattern.
LocalTime start = LocalTime.parse( "20:11:13" );
LocalTime stop = LocalTime.parse( "14:49:00" );
And define our test case, the target 01:00:00
.
LocalTime target = LocalTime.parse( "01:00:00" );
Now we are set up to compare these LocalTime
objects. We want to see if the target is after the later time but before the earlier time. That means middle of the night in this case, between approximately 8 PM and 3 AM the next morning.
Boolean isTargetAfterStartAndBeforeStop = ( target.isAfter( start ) && target.isBefore( stop ) ) ;
That test can be more simply stated as “not between 3 AM and 8 PM”. We could then generalize to any pair of LocalTime
objects where we test for between if the start comes before the stop with a 24-hour clock, and not between if start comes after the stop (as in the case of this Question).
Further more, spans of time are usually handled with the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a "between" comparison, strictly speaking, would be “is the target equal to or later than start AND the target is before stop”, or more simply, “is target not before start AND before stop”.
Boolean isBetweenStartAndStopStrictlySpeaking =
( ( ! target.isBefore( start ) && target.isBefore( stop ) ) ;
If the start is after the stop, within a 24-hour clock, then assume we want the logic suggested in the Question (is after 8 PM but before 3 AM).
if( start.isAfter( stop ) ) {
return ! isBetweenStartAndStopStrictlySpeaking ;
} else {
return isBetweenStartAndStopStrictlySpeaking ;
}
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
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.