Avoid Milliseconds
No need to mess with milliseconds for your purpose. Using milliseconds for date-time is confusing and error-prone.
What you need is a decent date-time library rather than the notoriously troublesome bundled java.util.Date & .Calendar classes.
Joda-Time
If you are certain you want to ignore dates and ignore time zones, here's some example code using the LocalTime
class offered by the third-party free-of-cost Joda-Time library.
LocalTime start = new LocalTime( 10, 0, 0 );
LocalTime stop = new LocalTime( 14, 30, 0 );
LocalTime target = LocalTime.now();
boolean isNowInSpan = !( ( target.isBefore( target ) ) | ( target.isAfter( stop ) ) );
Adjust that last line according to your business logic needs. You might want:
- The beginning and ending are inclusive
- The beginning and ending are exclusive
- "Half-Open" where the beginning is inclusive and the ending is exclusive
(usually best for date-time work)
Dump to console…
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "target: " + target );
System.out.println( "isNowInSpan: " + isNowInSpan );
When run…
start: 10:00:00.000
stop: 14:30:00.000
target: 23:49:37.779
isNowInSpan: false
Another Example
Time-of-day-only is not usually the right way to go. When new to date-time work, a naïve programmer may at first think that time-only simplifies things. On the contrary, this example shows how spinning around the clock creates complications. Using date+time+timeZone is usually the best approach in the long run.
LocalTime now = LocalTime.now();
LocalTime start = new LocalTime( 13, 0, 0, 0 );
LocalTime stop = start.plusHours( 11 );
System.out.println( "now: " + now );
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
if ( now.isAfter( start ) ) {
System.out.println( "After start" );
}
if ( now.isBefore( stop ) ) {
System.out.println( "Before stop" );
}
When run…
now: 14:00:32.496
start: 13:00:00.000
stop: 00:00:00.000
After start
java.time
Java 8 brings the new java.time package, inspired by Joda-Time, defined by JSR 310.
In java.time, you will find a LocalTime class similar to the one in Joda-Time.