Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
of
duration

What is Duration.of() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Overview

of() is a staticThe methods in Java that can be called without creating an object of the class. method of the Duration class. It is used to obtain a Duration object given the amount of duration and the specified unit of duration.

The of method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class, check the following import statement.

import java.time.Duration;

Syntax

public static Duration of(long amount, TemporalUnit unit)

Parameters

  • long amount: The amount of the duration. The value can be positive or negative.
  • TemporalUnit unit: The unit in which the duration is measured.

Return value

This method returns a Duration object.

Code

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
public class Main {
public static void main(String[] args){
long durationAmount = 10;
TemporalUnit temporalUnit = ChronoUnit.DAYS;
Duration duration = Duration.of(durationAmount, temporalUnit);
System.out.println("Duration object - " + duration);
}
}
Implementation of the of() method

Explanation

  • Lines 1–3: We import the relevant packages.
  • Line 8: We define the amount of the duration.
  • Line 9: We define the unit of measurement of the duration.
  • Line 10: We create a Duration object using the of() method by passing the durationAmount and temporalUnit as arguments.
  • Line 11: We print the Duration object created in line 10.

RELATED TAGS

java
communitycreator
of
duration

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring