Java Duration Class | ofHours() Method with Example

Duration Class ofHours() method: Here, we are going to learn about the ofHours() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 16, 2020

Duration Class ofHours() method

  • ofHours() method is available in java.time package.
  • ofHours() method is used to represent the given hours in this Duration.
  • ofHours() method is a static method, it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • ofHours() method may throw an exception at the time of representing hours.
    ArithmeticException: This exception may throw when the given hours' value exceeds the length of this Duration.

Syntax:

    public static Duration ofHours(long hrs_val);

Parameter(s):

  • long hrs_val – represents the number of hours in value.

Return value:

The return type of this method is Duration, it returns the Duration that holds the value of the given hours.

Example:

// Java program to demonstrate the example 
// of ofHours(long hrs_val) method of Duration

import java.time.*;

public class OfHoursOfDuration {
    public static void main(String args[]) {
        long hrs_val = 3;

        // returns the Duration that holds the value of the given
        // argument i.e. here we are representing
        // 3 hrs (3H) in this Duration du
        Duration du = Duration.ofHours(hrs_val);

        // Display du
        System.out.println("Duration.ofHours(3): " + du);
    }
}

Output

Duration.ofHours(3): PT3H


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.