What is TimeUnit.of in Java?

TimeUnit is an enum that deals with different units of time and the operations related to it. For example, it has different units of time such as nanoseconds, microseconds, milliseconds, seconds, minutes, hours, days, etc.

The of() method of TimeUnit is used to convert a ChronoUnit period unit to the equivalent TimeUnit representation.

What is ChronoUnit in Java?

A ChronoUnit is an enum that represents a standard set of date periods units. This set of units provide unit-based access to manipulate a date, time, or date-time.

Some examples of ChronoUnit period units are nanos, micros, seconds, half days, weeks, decades.

How to import the TimeUnit enum

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

import java.util.concurrent.TimeUnit;

Method signature

public static TimeUnit of(ChronoUnit chronoUnit)

Parameters

  • ChronoUnit chronoUnit: the ChronoUnit to convert.

Return value

The method returns the converted equivalent of the TimeUnit.

Code

In the code below, we create a ChronoUnit object.

Next, we check whether the method of() returns an object that is not null and is the instance of the TimeUnit class.

Then, we print the value returned by the method to the console.

import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
class Main {
public static void main(String[] args){
ChronoUnit chronoUnit = ChronoUnit.DAYS;
assert TimeUnit.of(chronoUnit) != null && TimeUnit.of(chronoUnit) instanceof TimeUnit;
System.out.println("Convert from TimeUnit to ChronoUnit - " + TimeUnit.of(chronoUnit));
}
}

Free Resources