Duration get() method in Java

Java 8ProgrammingObject Oriented Programming

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);
raja
Published on 13-Mar-2019 11:39:11
Advertisements