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.
TimeUnit
enumThe 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;
The signature of the convert()
method is as follows.
public long convert(long sourceDuration, TimeUnit sourceUnit)
long sourceDuration
: The time duration in the source unit.TimeUnit sourceUnit
: The time unit of the sourceDuration
argument.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
.
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));}}
In the code above, we convert time in milliseconds to time in minutes.
TimeUnit
object in the target time unit, i.e., MINUTES
.convert
method in line 7, by passing the duration and the source time unit, i.e., MILLISECONDS
.