Duration get() method in Java


The value of the chronological unit can be obtained using the method get() in the Duration class in Java. This method requires a single parameter i.e. the TemporalUnit for which the value is required. Also, the value of the chronological unit is returned by this method.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.Duration;
import java.time.temporal.*;
public class Demo {
   public static void main(String[] args) {
      Duration d = Duration.ofMinutes(2);
      System.out.println("The duration in minutes is: " + d);
      long seconds = d.get(ChronoUnit.SECONDS);
      System.out.println("The duration in seconds is: " + seconds);
   }
}

Output

The duration in minutes is: PT2M
The duration in seconds is: 120

Now let us understand the above program.

The value of the chronological unit is obtained using the method get() and then this is printed. A code snippet that demonstrates this is as follows −

Duration d = Duration.ofMinutes(2);
System.out.println("The duration in minutes is: " + d);
long seconds = d.get(ChronoUnit.SECONDS);
System.out.println("The duration in seconds is: " + seconds);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements