Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | toHours() Method with Example
Duration Class toHours() method: Here, we are going to learn about the toHours() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 17, 2020
Duration Class toHours() method
- toHours() method is available in java.time package.
- toHours() method is used to convert this Duration into the number of hours.
- toHours() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
- toHours() method does not throw an exception at the time of converting this Duration to hours.
Syntax:
public long toHours();
Parameter(s):
Return value:
The return type of this method is long, it returns the number of hours exists in this Duration.
Example:
// Java program to demonstrate the example
// of long toHours() method of Duration
import java.time.*;
public class ToHoursOfDuration {
public static void main(String args[]) {
// Instantiates two Duration objects
Duration du1 = Duration.ofMinutes(305);
Duration du2 = Duration.parse("P0DT0H60M10S");
// Display du1 and du2
System.out.println("du1: " + du1);
System.out.println("du2: " + du2);
// represents this Duration du1 in minutes into
// number of hours i.e. 305M 5H:5M
long to_hours = du1.toHours();
// Display to_hours
System.out.println("du1.toHours(): " + to_hours);
// represent this Duration du2 in minutes into
// number of hours i.e. 60M10S = 1H 10S hours
to_hours = du2.toHours();
// Display to_hours
System.out.println("du2.toHours(): " + to_hours);
}
}
Output
du1: PT5H5M
du2: PT1H10S
du1.toHours(): 5
du2.toHours(): 1