Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is TimeUnit.convert() 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

TimeUnit is an enum that deals with different units of time and operations related to it. For example, it has different units of time like NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, and DAYS.

The convert() method of TimeUnit is used to convert a time duration from one unit to another unit.

How to import the TimeUnit enum

The TimeUnit enum is defined in the java.util.concurrent package. You can use the import statement below to import the TimeUnit enum.

import java.util.concurrent.TimeUnit;

Method signature

The signature of the convert() method is as follows.

public long convert(long sourceDuration, TimeUnit sourceUnit)

Parameters

  • long sourceDuration: The time duration in the source unit.
  • TimeUnit sourceUnit: The time unit of the sourceDuration argument.

Return value

The convert() method returns either the converted time duration or, if the conversion overflows negatively, it returns Long.MIN_VALUE. Similarly, if the conversion overflows positively, it returns Long.MAX_VALUE.

Code

The code below shows how the convert() method can be used in Java.

import java.util.concurrent.TimeUnit;
class Main {
public static void main(String[] args){
long timeInMillis = 60000L;
TimeUnit time = TimeUnit.MINUTES;
System.out.println("Time in milliseconds - " + timeInMillis + "\nconverted to minutes - " + time.convert(timeInMillis, TimeUnit.MILLISECONDS));
}
}

Explanation

In the code above, we convert time in milliseconds to time in minutes.

  1. We construct a TimeUnit object in the target time unit, i.e., MINUTES.
  2. We convert the object above to minutes with the help of the convert method in line 7, by passing the duration and the source time unit, i.e., MILLISECONDS.

RELATED TAGS

java
communitycreator

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