Learn to create and use the LocalTime class in Java. Learn how to create LocalTime, parse and format the LocalTime instances, including common operations such as adding or subtracting hours from a given time.
1. Overview
java.time.LocalTime class, introduced in Java 8 Date APIs, represents the local time (hours, minutes, seconds) without any date or timezone information. LocalTime represents the time to nanosecond precision e.g. 09:25:59.123456789
We can use the LocalTime
instances to represent a time as seen in a wall clock without any need of the date or timezone. For example, we can use LocalTime
to mention the office opening and closing time, everyday.
Note that LocalTime
instances are immutable and thread-safe.
In Java source code, LocalTime class has been defined as Comparable and Serializable.
2. Creating LocalTime
Generally, we will be creating local time instances in two conditions i.e. get current time or create local time for a specified timestamp.
2.1. Getting Current Time
Use now() method to get the current time.
2.2. Creating Local Time with Values
To create a local time with specific hours, minutes and seconds – use of(hour, minutes, seconds, millis) method. It is an overloaded method and takes a variable number of parameters.
2.3. Parsing String
We can use the parse() method to get the time from a string.
3. Parsing to LocalTime
The LocalTime
class has two overloaded parse() methods to convert time in a string to LocalTime instance.
- Use first method if the string contains time in
ISO_LOCAL_TIME
pattern i.e. [HH]:[mm]:[ss]. This is default pattern of local time in Java. - For any other time pattern, we need to use second method where we pass the time as string as well as a formatter which represents the pattern of that time string.
4. Formatting LocalTime
Use LocalTime.format(DateTimeFormatter)
method to format a local time to the desired string representation.
5. Modifying the Time
LocalTime
provides below methods which can be used to get to new local time instance relative to available local time instance.
plusHours()
plusMinutes()
plusSeconds()
plusNanos()
minusHours()
minusMinutes()
minusSeconds()
minusNanos()
6. Conclusion
In this tutorial, we learned about the LocalTime class that is used to represent the local time (hours, minutes, seconds) without any date or timezone information in nano-second precision.
We learned to create an instance of LocalTime, parse a string to LocalTime and then formatting the LocalTime instance. We also learned to add and subtract the time from a LocalTime instance.
Happy Learning !!
Comments