Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
enum

What is TimeUnit.of 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.

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));
}
}

RELATED TAGS

java
enum

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