In this source code example, we show you how to add hours to time in Java using Java 8 LocalTime class.
Add hours to time in Java
package com.ramesh.java8.datetime;
import java.time.LocalTime;
/**
* Useful Java8DateUtiliy Methods
* @author javaguides.net
*
*/
public final class Java8DateUtility {
/**
* Add hours to time.
* @param hours
* @return
*/
public static LocalTime addHoursToTime(int hours) {
LocalTime time = LocalTime.now();
LocalTime newTime = time.plusHours(hours); // adding two hours
System.out.println("Time after 2 hours : " + newTime);
return newTime;
}
}
JUnit test case
package com.ramesh.java8.datetime;
import org.junit.Test;
/**
* JUnit test cases for Java8DateUtiliy Methods
* @author javaguides.net
*
*/
public class Java8DateUtilityTest {
@Test
public void addHoursToTime() {
System.out.println("Added hours to time :: " + Java8DateUtility.addHoursToTime(1));
}
}
Run the JUnit test cases will print the output:
Added hours to time :: 19:40:51.641