What is TimeUnit.convert() in Java?

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.

Free Resources