How can I convert one specific hour, e.g. 18:00, to milliseconds?
I need this so that if it's between for example 12:00 and 18:00 I can do something, and if it is not between 12:00 and 18:00 I can do something else.
I get the current time with:
Private long time;
time = System.currentTimeMillis();
But I don't know how to convert an hour to milliseconds.
I searched on the Internet and it seems that if I use System.currentTimeMillis()
it will give me the millisecond of the current day and hour but I need it to update for every day something like this:
Today the time in millis is something like this: 1516994140294
. But this number contains this: Fri Jan 26 2018 19:15:40
. So if I use the millis for 12:00 and 18:00 of this day this means that tomorrow it will not work as I want.
So can you help me with an example or documentation? Everything can help me :) and thanks in advance.
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 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
.
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?