Java LocalTime
Jakob Jenkov |
The LocalTime
class in the Java 8 date time API represents a specific time of day without any
time zone information. For instance, 10.00 AM . The LocalTime
instance can be used to describe
e.g. when school or work starts in different countries, where you are not interested in the UTC time, but the
time in the respective countries. Of course you could also represent that as UTC time with a time zone, but you
can also just use a LocalTime
object without time zone information.
The LocalTime
class is immutable, so all calculations on LocalTime
objects return
a new LocalTime
instance.
Creating a LocalTime Object
You can create a LocalTime
instance in several ways. The first way is to create a LocalTime
instance that represents the exact time of now. Here is how that looks:
LocalTime localTime = LocalTime.now();
Another way to create a LocalTime
object is to create it from a specific amount of hours, minutes,
seconds and nanoseconds. Here is how that looks:
LocalTime localTime2 = LocalTime.of(21, 30, 59, 11001);
There are also other versions of the of()
method that only takes hours and minutes, or hours, minutes
and seconds as parameters.
Accessing the Time of a LocalTime Object
You can access the hours, minutes, seconds and nanosecond of a LocalTime
object using these
methods:
getHour()
getMinute()
getSecond()
getNano()
LocalTime Calculations
The LocalTime
class contains a set of methods that enable you to perform local time calculations.
Some of these methods are:
plusHours()
plusMinutes()
plusSeconds()
plusNanos()
minusHours()
minusMinutes()
minusSeconds()
minusNanos()
Here is an example that shows how these methods work:
LocalTime localTime2 = LocalTime.of(21, 30, 59, 11001); LocalTime localTimeLater = localTime.plusHours(3); LocalTime localTimeEarlier = localTime.minusHours(3);
The first line creates a LocalTime
instance representing the time of day 21:30:50 and 11001 nanoseconds.
The second line creates a LocalTime
instance that represents a time 3 hours later. The third line
creates a LocalTime
instance that represents a time 3 hours earlier.
Tweet | |
Jakob Jenkov |