What is TimeUnit.toChronoUnit() in Java?

Overview

The TimeUnit is an enumshort for enumeration 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
  • Days

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

What is ChronoUnit in Java?

A ChronoUnit is an enum that represents a standard set of date periods units.

This set of units provides unit-based access to manipulate a date, time, or date-time.

Some examples of ChronoUnit period units are:

  • Nanos
  • Micros
  • Seconds
  • Half_day
  • 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;

Syntax


public ChronoUnit toChronoUnit()

Parameters

The method doesn’t take any parameters.

Return value

The method returns the converted equivalent of the ChronoUnit date period unit.

Code

  • In the code below, we create a TimeUnit object.

  • Then we check whether the method toChronoUnit() returns an object that is not null as is the instance of the ChronoUnit class.

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

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

Output

Convert from TimeUnit to ChronoUnit - Minutes