Java Reference
In-Depth Information
Current Time: 22:21:08.419
Local Date Time object: 2011-11-11T22:21:08.419
Comparing times: 1
Hour: 22
Is local time after pastTime? true
Time minus 5 hours: 17:21:08.419
Time plus 30 mins: 22:51:08.419
How It Works
Sometimes it is necessary to obtain the current system time. The
LocalTime
class
can be used to obtain the current time by calling its
now()
method. Similarly to the
LocalDate
class, the
LocalTime.now()
method can be called to return a
LocalTime
object that is equal to the current time. The
LocalTime
class also con-
tains several methods that can be utilized to manipulate the time. The examples con-
tained in the solution provide a brief overview of the available methods.
Let's take a look at a handful of examples to provide some context for how the
LocalTime
methods are invoked. To obtain a
LocalTime
object set to a specific
time, invoke the
LocalTime.of(int, int)
method, passing
int
parameters
representing the hour and minute.
// of(int hours, int min): obtain a specific time
LocalTime pastTime = LocalTime.of(1, 10);
The
atDate(LocalDate)
instance method is used to apply a
LocalDate
ob-
ject to a
LocalTime
instance, returning a
LocalDateTime
object (for more in-
formation, see Recipe 4-11).
LocalDateTime ldt
= time.atDate(LocalDate.of(2011,Month.NOVEMBER,11));
There are several methods that can be used for obtaining portions of the time. For
instance, the
getHour()
,
getMinute()
,
getNano()
, and
getSecond()
meth-
ods can be used to return those specified portions of the
LocalTime
object.
int hour = time.getHour();
int min = time.getMinute();