Java Duration Class | get() Method with Example

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

Duration Class get() method

  • get() method is available in java.time package.
  • get() method is used to return the value for the given unit.
  • get() 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.
  • get() method may throw an exception at the time of returning value for the given unit.
    • DateTimeException: This exception may throw when the given amt couldn’t convert into a Duration.
    • UnsupportedTemporalTypeException: This exception may throw when the given unit is unsupported.

Syntax:

    public long get(TemporalUnit t_unit);

Parameter(s):

  • TemporalUnit t_unit – represents the temporal unit of the returned value.

Return value:

The return type of this method is long, it returns the value for the given temporal unit.

Example:

// Java program to demonstrate the example 
// of long get(TemporalUnit t_unit) method of Duration

import java.time.*;
import java.time.temporal.*;

public class GetOfDuration {
    public static void main(String args[]) {
        // Instantiates two Duration objects
        Duration du1 = Duration.ofHours(1);
        Duration du2 = Duration.ofMinutes(5);

        // Display du1 and du2
        System.out.println("du1: " + du1);
        System.out.println("du2: " + du2);

        // gets the value of the given unit i.e. 
        // here we are requesting the value of 
        // du1 in SECONDS unit
        long get_val = du1.get(ChronoUnit.SECONDS);

        // Display get_val
        System.out.println("du1.get(ChronoUnit.SECONDS): " + get_val);

        // gets the value of the given unit i.e. 
        // here we are requesting the value of 
        // du2 in SECONDS unit
        get_val = du2.get(ChronoUnit.SECONDS);

        // Display get_val
        System.out.println("du2.get(ChronoUnit.SECONDS): " + get_val);
    }
}

Output

du1: PT1H
du2: PT5M
du1.get(ChronoUnit.SECONDS): 3600
du2.get(ChronoUnit.SECONDS): 300



Comments and Discussions!

Load comments ↻






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