Java Convert ChronoUnit to TimeUnit

Tags: TimeUtil ChronoUnit TimeUnit

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

How to convert ChronoUnit to TimeUnit in Java

Firstly, we create a new Java utility class named TimeUtil, and implement a new method named convertToTimeUnit(ChronoUnit chronoUnit) to get ChronoUnit object in argument and convert it to TimeUnit as a return value.

TimeUtil.java

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

public class TimeUtil {

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

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

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

ConvertChronoUnitToTimeUnitExample.java

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

public class ConvertChronoUnitToTimeUnitExample {
    public static void main(String... args) {
        ChronoUnit chronoUnit1 = ChronoUnit.DAYS;
        ChronoUnit chronoUnit2 = ChronoUnit.SECONDS;
        ChronoUnit chronoUnit3 = null;

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

        System.out.println("timeUnit1: " + timeUnit1);
        System.out.println("timeUnit2: " + timeUnit2);
        System.out.println("timeUnit3: " + timeUnit3);
    }
}
The output as below.
timeUnit1: DAYS
timeUnit2: SECONDS
timeUnit3: null

Happy Coding 😊

Java Convert TimeUnit to ChronoUnit

Java Convert Number of Hours to Days

Java Convert Number of Minutes to Hours

Java Convert Number of Seconds to Minutes