tl;dr
LocalTime.now() // Capture current moment. Better to explicitly pass a `ZoneId` object than rely implicitly on the JVM’s current default time zone.
.isBefore( LocalTime.of( 18 , 0 ) ) // Compare the current time-of-day against the limit.
No need for milliseconds count
No need to count milliseconds. Java has smart date-time classes for this work, found in the java.time package built into Java 8 and later. For earlier Android, see the last bullets below.
No need for System.currentTimeMillis()
. The java.time classes do the same job.
LocalTime
To get the current time of day, without a date and without a time zone, use LocalTime
.
Determining the current time requires a time zone. For any given moment, the time-of-day varies by zone. If omitted, the JVM’s current default time zone is applied implicitly. Better to explicitly specify your desired/expected time zone, as the default may change at any moment before or during runtime.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalTime now = LocalTime.now( z ) ;
Compare with methods isBefore
, isAfter
, and equals
.
A shorter way of asking "is equal to or later than noon" is "is not before noon".
boolean isAfternoon =
( ! now.isBefore( LocalTime.NOON ) )
&&
now.isBefore( LocalTime.of( 18 , 0 ) )
;
If you are concerned about the effects of anomalies such as Daylight Saving Time( DST), explore the use of ZonedDateTime
instead of mere LocalTime
.
About java.time
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.
Where to obtain the java.time classes?