Updated March 20, 2023
Introduction to Java LocalTime
Java LocalTime is one of the in-built functional packages that can be used for multiple operations related to date and time. For LocalTime related operations, Java has a specific application program interface (API) called Java Time, which holds multiple methods for it to be applied to any date and time-related functions. Some of the commonly used methods in the LocalTime class are get(), compareTo(), equals, atDate(), of(), now(), plusHours(), minusHours(), etc with hours, minutes and seconds as their pre-defined objects.
Now that we have understood the LocalTime class of Java 8 let’s learn the Syntax.
Syntax:
public final class LocalTime extends Object implements Comparable<LocalTime>
The above syntax is a standard way of initializing the class. As mentioned earlier, the LocalTime class extends the Object class and does implement a comparable interface.
Methods of Java LocalTime
Let us now explore the methods offered with the LocalTime class.
public LocalDateTime atDate(LocalDate date)
1. atDate(): To create a LocalDateTime, it combines this time with a date. Takes the date to combine with as a parameter, does not accept null. Here, all the possible date and time combinations are valid.
public int compareTo(LocalTime other)
2. compareTo(): Simply compares this time with any other passed time. Takes the other time which is to be compared with as a parameter. Returns a value of comparison. Positive if greater and negative if less. In case if the other value is not passed or fails to pass, it does throw a NullPointerException.
public int get(TemporalField field)
3. get(): Gets the value from this time as an Integer. Takes a field to get as a parameter, does not accept Null. And returns the value for the field. The return value is always in the range. In case if it fails to return the value due to any reason, an exception is thrown.
4. Exceptions: Throws DateTimeException if the value is outside the range or if unable to obtain the value. And ArithmeticException is thrown in case the numeric overflow happens.
public boolean equals(Object obj)
5. equals: Simple comparison between this time and any other time. It takes in an object to check as a parameter, and null is returned in case of false value. It overrides the equals in Class Object. Here, only the objects of the type LocalTime are compared; in the case of other types, it returns false.
public static LocalTime now()
6. now(): In the default time zone, now() fetches the current time from the system. Never Null always returns the current system time.
public static LocalTime now(ZoneId zone)
7. now(ZoneId zone): Similar to above, but with the specified time zone. it Takes zone ID as a parameter, do not accept null. Returns the current time for the passed time zone.
public static LocalTime of(int hour, int minute, int second, int nanoOfSecond):
8. of(): An instance of LocalTime is obtained. Takes four parameters as an hour, minute, second, nanoseconds and returns the local time, never null. In case if the value happens to be out of range, it throws DateTimeException.
public LocalTime minusHours(long hoursToSubtract):
9. minusHours(): Copy of this LocalTime is returned with the number of hours subtracted. Take hoursToSubtract as the parameter; it must not be negative. And returns, this LocalTime, with subtracted number of hours. The instance here is immutable and is unaffected by the method call.
public LocalTime plusHours(long hoursToAdd):
10. plusHours(): Exact opposite of the method mentioned above. Returns a copy of this LocalTime with a number of specified hours added. Similar to the above, it is immutable and unaffected.
Examples to Implement Java LocalTime
Now that we have understood the methods above let us try to demonstrate these methods into examples.
Example #1
Code:
public class localtime {
public static void main(String[] args) {
LocalTime time_now = LocalTime.now();
System.out.println(time_now);
}
}
Code Interpretation: For example 1, we have simply implemented the now() method of LocalTime class. Created a class, then the main class followed by the method call and a simple output statement. Upon execution, it will return the current system time. The output will be in the format of Hour, Minute, Seconds and Mini Second. Refer below the screenshot for output.
Output:
Example #2
Code:
import java.time.LocalTime;
public class localtime {
public static void main(String[] args) {
LocalTime time_1 = LocalTime.of(10,43,12);
System.out.println(time_1);
LocalTime time_2=time_1.minusHours(3);
LocalTime time_3=time_2.minusMinutes(41);
System.out.println(time_3);
}
}
Code Interpretation: Here, we have demonstrated two methods, minusHours() and minusMinutes(). After creating our class and main class, we called the () method with parameters and printed the next line’s output. Later, we created two objects with two methods, respectively, for hours and for minutes. So, out of the given time in of() method, the number of hours to be subtracted will be 2, and minutes will be 41. With that in mind, our output should be 10-3 hours, which is 7 hours and 43-41 minutes, which will be 2 minutes. So, the final output must be “07:02:12”. For sample output, refer to the below attached screenshot.
Output:
Example #3
Code:
import java.time.*;
public class localtime {
public static void main(String[] args) {
LocalTime time1 = LocalTime.parse("13:08:00");
LocalTime time_now = LocalTime.now();
System.out.println("LocalTime1: " + time1);
System.out.println("LocalTime2: " + time_now);
boolean eq_value = time1.equals(time_now);
System.out.println("Both times are equal: " + eq_value);
}
}
Code Interpretation: In our 3rd example, we have implemented the equals method. Other than the creation of class and the main class, we have two objects with assigned values. At first, we have passed a specific time, and for the second, we have fetched the current time of the system with the now() method. Later, we have printed these two values and then a boolean comparison. Using the equals() method, we have compared the two times and passed the output to the output print statement. The equals method’s output will be either true or false; based on the values passed here, the output here must be false. Refer below the screenshot for output.
Output:
Conclusion
Java 8’s Date Time update comes with many features, and LocalTime is one of them, which does not store any value but is a better representation of the date and time. We understood the methods with description and followed by three example samples. LocalTime class of java provides a wide range of methods, more than mentioned and can be used as per requirement.
Recommended Articles
This is a guide to Java LocalTime. Here we discuss the basic concept, methods and parameters of Java LocalTime along with the examples. You may also have a look at the following articles to learn more –