Duration of() method in Java


The required duration using a particular temporal unit can be calculated with the method of() in the Duration class in Java. This method requires two parameters i.e. the time value and the temporal unit for that value. It returns the time duration with the particular value and temporal unit.

A program that demonstrates this is given as follows −

Example

 Live Demo

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

Output

The duration in minutes is: 120

Now let us understand the above program.

The time duration with the value 2 and temporal unit HOURS is calculated with the method of(). Then this duration is displayed in the form of minutes. A code snippet that demonstrates this is as follows −

long timeValue = 2;
Duration d = Duration.of(timeValue, ChronoUnit.HOURS);
System.out.println("The duration in minutes is: " + d.toMinutes());

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements