Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

What is DurationUtils.toDuration() 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.

The toDuration() method

toDuration() is a staticthe methods in Java that can be called without creating an object of the class method of the DurationUtils class that is used to convert a given amount of duration and TimeUnit into an instance of the Duration class.

How to import DurationUtils

The definition of DurationUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:


<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the DurationUtils class as follows:


import org.apache.commons.lang3.time.DurationUtils;

Syntax


public static Duration toDuration(final long amount, final TimeUnit timeUnit)

Parameters

  • final long amount: The amount of the duration; this parameter can be positive or negative.
  • final TimeUnit timeUnit: Unit of duration measurement.

Return value

This method returns an instance of the Duration class.

Code

In the code below, we get an instance of the Duration object of 10 minutes.

import org.apache.commons.lang3.time.DurationUtils;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
public class Main{
public static void main(String[] args) {
int amount = 10;
TimeUnit timeUnit = TimeUnit.MINUTES;
Duration duration = DurationUtils.toDuration(amount, timeUnit);
System.out.printf("DurationUtils.toDuration(%s, %s) = %s", amount, timeUnit, duration);
}
}

Output

The output of the code is as follows:


DurationUtils.toDuration(10, MINUTES) = PT10M

RELATED TAGS

java

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.

Keep Exploring