Java Convert TimeUnit to ChronoUnit

Tags: TimeUtil ChronoUnit TimeUnit

In this Java core tutorial, we learn how to convert a java.util.concurrent.TimeUnit object into a java.time.temporal.ChronoUnit object in Java programming language.

How to convert TimeUnit to ChronoUnit in Java

In this first step, we create a new Java class named TimeUtil, and implement new static method named convertToChronoUnit(TimeUnit timeUnit) to get a TimeUnit object as argument and convert it to ChronoUnit as a return value.

TimeUtil.java

import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

public class TimeUtil {

    /**
     * Convert TimeUnit object to ChronoUnit object
     * @param timeUnit the TimeUnit object
     * @return the ChronoUnit object
     */
    public static ChronoUnit convertToChronoUnit(TimeUnit timeUnit) {
        if(timeUnit == null) {
            return null;
        }

        switch (timeUnit) {
            case NANOSECONDS:
                return ChronoUnit.NANOS;
            case MICROSECONDS:
                return ChronoUnit.MICROS;
            case MILLISECONDS:
                return ChronoUnit.MILLIS;
            case SECONDS:
                return ChronoUnit.SECONDS;
            case MINUTES:
                return ChronoUnit.MINUTES;
            case HOURS:
                return ChronoUnit.HOURS;
            case DAYS:
                return ChronoUnit.DAYS;
            default:
                return null;
        }
    }
}

In the following example Java program, we show how to use the TimeUtil class above to convert TimeUnit objects into ChronoUnit objects.

ConvertTimeUnitToChronoUnitExample.java

import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

public class ConvertTimeUnitToChronoUnitExample {
    public static void main(String... args) {
        TimeUnit timeUnit1 = TimeUnit.DAYS;
        TimeUnit timeUnit2 = TimeUnit.SECONDS;
        TimeUnit timeUnit3 = null;

        // Convert TimeUnit to ChronoUnit
        ChronoUnit chronoUnit1 = TimeUtil.convertToChronoUnit(timeUnit1);
        ChronoUnit chronoUnit2 = TimeUtil.convertToChronoUnit(timeUnit2);
        ChronoUnit chronoUnit3 = TimeUtil.convertToChronoUnit(timeUnit3);

        System.out.println("chronoUnit1: " + chronoUnit1);
        System.out.println("chronoUnit2: " + chronoUnit2);
        System.out.println("chronoUnit3: " + chronoUnit3);
    }
}
The output as below.
chronoUnit1: Days
chronoUnit2: Seconds
chronoUnit3: null

Happy Coding 😊

Java Convert ChronoUnit to TimeUnit

Java Convert Number of Hours to Days

Java Convert Number of Minutes to Hours

Java Convert Number of Seconds to Minutes