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.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
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
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.
The above is the detailed content of Java LocalTime. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
