In this guide, you will learn about the LocalTime plusHours() method in Java programming and how to use it with an example.
1. LocalTime plusHours() Method Overview
Definition:
The plusHours() method of the LocalTime class in Java is utilized to add the specified number of hours to the current LocalTime instance, returning a new LocalTime object representing the result.
Syntax:
public LocalTime plusHours(long hoursToAdd)
Parameters:
- hoursToAdd: the hours to add, may be negative.
Key Points:
- The plusHours() method returns a new LocalTime instance with the specified hours added to the original time.
- The original LocalTime object remains unmodified, as LocalTime instances are immutable.
- If the addition results in a time beyond 24 hours, the hour value wraps around.
- The method does not affect the minute, second, or nanosecond values of the LocalTime.
- If hoursToAdd is negative, the method effectively subtracts the absolute value of the hours from the current time.
2. LocalTime plusHours() Method Example
import java.time.LocalTime;
public class LocalTimePlusHoursExample {
public static void main(String[] args) {
// Get the current LocalTime
LocalTime currentTime = LocalTime.now();
System.out.println("Current Local Time: " + currentTime);
// Add 5 hours to the current LocalTime
LocalTime timeAfterAddingHours = currentTime.plusHours(5);
System.out.println("Local Time After Adding 5 Hours: " + timeAfterAddingHours);
// Subtract 3 hours from the current LocalTime using negative parameter
LocalTime timeAfterSubtractingHours = currentTime.plusHours(-3);
System.out.println("Local Time After Subtracting 3 Hours: " + timeAfterSubtractingHours);
}
}
Output:
Current Local Time: 10:15:30.123456789 (example time, actual output will vary) Local Time After Adding 5 Hours: 15:15:30.123456789 Local Time After Subtracting 3 Hours: 07:15:30.123456789
Explanation:
In this example, we first retrieve the current LocalTime and print it to the console.
We then use the plusHours() method to add 5 hours to the current time, resulting in a new LocalTime instance which is printed to the console.
Subsequently, we demonstrate the subtraction of hours by passing a negative value to plusHours(), subtracting 3 hours from the current time, and printing the resulting LocalTime to the console.
Comments
Post a Comment
Leave Comment