Duration get(TemporalUnit) method in Java with Examples

The get(TemporalUnit) method of Duration Class in java.time package is used to get the value of the unit passed as the parameter. Only units SECONDS and NANOS ate supported by this method and the rest result in exception.

Syntax:

public long get(TemporalUnit unit)

Parameters: This method accepts a parameter unit which is the TemporalUnit for which the value is to be fetched.



Return Value: This method returns a long value of the unit passed as the parameter.

Exception: This method throws:

  • DateTimeException: if the unit is not supported.
  • UnsupportedTemporalTypeException: if the unit is not supported.

Below examples illustrate the Duration.get() method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate get() method
  
import java.time.Duration;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the text
        String time = "P2DT3H4M";
  
        // Duration using parse() method
        Duration duration = Duration.parse(time);
  
        // Duration using get() method
        long getSeconds
            = duration.get(ChronoUnit.SECONDS);
  
        System.out.println("Seconds: "
                           + getSeconds);
  
        // Duration using get() method
        long getNanos
            = duration.get(ChronoUnit.NANOS);
  
        System.out.println("Nanos: "
                           + getNanos);
    }
}

chevron_right


Output:

Seconds: 183840
Nanos: 0

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate get() method
  
import java.time.Duration;
import java.time.temporal.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the text
        String time = "P2DT3H4M";
  
        // Duration using parse() method
        Duration duration
            = Duration.parse(time);
  
        try {
            // Duration using get() method
            long getMinutes
                = duration.get(ChronoUnit.MINUTES);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

chevron_right


Output:

Exception:
 java.time.temporal.UnsupportedTemporalTypeException:
 Unsupported unit: Minutes

Reference: Oracle Doc



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.