Java : TimeUnit with Examples

TimeUnit (Java SE 18 & JDK 18) API Examples.
You will find code examples on most TimeUnit methods.


Summary

A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.

Class diagram

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var future = executorService.submit(() -> "abcd");

    final var ret = future.get();
    System.out.println(ret); // abcd

} finally {
    executorService.shutdown();
}

final var ret = executorService.awaitTermination(1, TimeUnit.MINUTES);
System.out.println(ret); // true
final var start = System.nanoTime();

// Equivalent to Thread.sleep(5000).
TimeUnit.SECONDS.sleep(5);

final var end = System.nanoTime();

// 5.001643 sec.
System.out.printf("%f sec.%n", (end - start) / 1000000000.0);

Enum Constants

DAYS

Time unit representing twenty four hours.

System.out.println(TimeUnit.DAYS); // DAYS
System.out.println(TimeUnit.DAYS.toHours(1)); // 24

HOURS

Time unit representing sixty minutes.

System.out.println(TimeUnit.HOURS); // HOURS
System.out.println(TimeUnit.HOURS.toMinutes(1)); // 60

MICROSECONDS

Time unit representing one thousandth of a millisecond.

System.out.println(TimeUnit.MICROSECONDS); // MICROSECONDS
System.out.println(TimeUnit.MICROSECONDS.toNanos(1)); // 1000

MILLISECONDS

Time unit representing one thousandth of a second.

System.out.println(TimeUnit.MILLISECONDS); // MILLISECONDS
System.out.println(TimeUnit.MILLISECONDS.toMicros(1)); // 1000

MINUTES

Time unit representing sixty seconds.

System.out.println(TimeUnit.MINUTES); // MINUTES
System.out.println(TimeUnit.MINUTES.toSeconds(1)); // 60

NANOSECONDS

Time unit representing one thousandth of a microsecond.

System.out.println(TimeUnit.NANOSECONDS); // NANOSECONDS
System.out.println(TimeUnit.NANOSECONDS.toSeconds(1000000000)); // 1

SECONDS

Time unit representing one second.

System.out.println(TimeUnit.SECONDS); // SECONDS
System.out.println(TimeUnit.SECONDS.toMillis(1)); // 1000

Methods

long convert (long sourceDuration, TimeUnit sourceUnit)

Converts the given time duration in the given unit to this unit.

final var ret1 = TimeUnit.HOURS.convert(1, TimeUnit.DAYS);
System.out.println(ret1); // 24

final var ret2 = TimeUnit.MINUTES.convert(2, TimeUnit.HOURS);
System.out.println(ret2); // 120

final var ret3 = TimeUnit.MILLISECONDS.convert(3, TimeUnit.SECONDS);
System.out.println(ret3); // 3000
final var ret1 = TimeUnit.SECONDS.convert(1000, TimeUnit.MILLISECONDS);
System.out.println(ret1); // 1

final var ret2 = TimeUnit.SECONDS.convert(999, TimeUnit.MILLISECONDS);
System.out.println(ret2); // 0
// An example with overflow.
final var ret1 = TimeUnit.NANOSECONDS.convert(100000000, TimeUnit.DAYS);
System.out.println(ret1 == Long.MAX_VALUE); // true

final var ret2 = TimeUnit.NANOSECONDS.convert(-100000000, TimeUnit.DAYS);
System.out.println(ret2 == Long.MIN_VALUE); // true

long convert (Duration duration)

Converts the given time duration to this unit.

final var ret1 = TimeUnit.HOURS.convert(Duration.ofDays(1));
System.out.println(ret1); // 24

final var ret2 = TimeUnit.MINUTES.convert(Duration.ofHours(2));
System.out.println(ret2); // 120

final var ret3 = TimeUnit.MILLISECONDS.convert(Duration.ofSeconds(3));
System.out.println(ret3); // 3000

static TimeUnit of (ChronoUnit chronoUnit)

Converts a ChronoUnit to the equivalent TimeUnit.

final var ret1 = TimeUnit.of(ChronoUnit.DAYS);
System.out.println(ret1); // DAYS

final var ret2 = TimeUnit.of(ChronoUnit.SECONDS);
System.out.println(ret2); // SECONDS

void sleep (long timeout)

Performs a Thread.sleep using this time unit.

final var start = System.nanoTime();

// Equivalent to Thread.sleep(5000).
TimeUnit.SECONDS.sleep(5);

final var end = System.nanoTime();

// 5.001643 sec.
System.out.printf("%f sec.%n", (end - start) / 1000000000.0);
final var start = System.nanoTime();

TimeUnit.MINUTES.sleep(1);

final var end = System.nanoTime();

// 60.000510 sec.
System.out.printf("%f sec.%n", (end - start) / 1000000000.0);

void timedJoin (Thread thread, long timeout)

Performs a timed Thread.join using this time unit.

final var thread = new Thread(() -> {
    try {
        System.out.println("task : start");
        TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
        System.out.println("Interrupted!");
    } finally {
        System.out.println("task : end");
    }
});

System.out.println("-- start --");
thread.start();

System.out.println("-- join start --");
TimeUnit.SECONDS.timedJoin(thread, 3);

System.out.println("-- join end --");

// Result
// ↓
//-- start --
//-- join start --
//task : start
//task : end
//-- join end --

void timedWait (Object obj, long timeout)

Performs a timed Object.wait using this time unit.

final long current = System.nanoTime();

final DoubleSupplier elapsedSec = () -> (System.nanoTime() - current) / 1000000000.0;

final var executorService = Executors.newSingleThreadExecutor();
try {
    final var obj = new Object();
    final Callable<Void> task = () -> {
        try {
            System.out.printf("task start : %f sec.%n", elapsedSec.getAsDouble());
            synchronized (obj) {
                TimeUnit.SECONDS.timedWait(obj, 2);
            }
        } finally {
            System.out.printf("task end : %f sec.%n", elapsedSec.getAsDouble());
        }
        return null;
    };

    executorService.submit(task);

    TimeUnit.SECONDS.sleep(5);

    synchronized (obj) {
        obj.notify();
    }

} finally {
    executorService.shutdown();
    System.out.printf("--- shutdown --- : %f sec.%n", elapsedSec.getAsDouble());
}

final var ret = executorService.awaitTermination(10, TimeUnit.SECONDS);
System.out.printf("termination %b : %f sec.%n", ret, elapsedSec.getAsDouble());

// Result
// ↓
//task start : 0.002766 sec.
//task end : 2.016894 sec.
//--- shutdown --- : 5.031749 sec.
//termination true : 5.033790 sec.

ChronoUnit toChronoUnit ()

Converts this TimeUnit to the equivalent ChronoUnit.

final var ret1 = TimeUnit.HOURS.toChronoUnit();
System.out.println(ret1); // Hours

final var ret2 = TimeUnit.MINUTES.toChronoUnit();
System.out.println(ret2); // Minutes

final var ret3 = TimeUnit.SECONDS.toChronoUnit();
System.out.println(ret3); // Seconds

long toDays (long duration)

Equivalent to DAYS.convert(duration, this).

final var ret1 = TimeUnit.HOURS.toDays(48);
System.out.println(ret1); // 2

final var ret2 = TimeUnit.MINUTES.toDays(24 * 60 * 10);
System.out.println(ret2); // 10

long toHours (long duration)

Equivalent to HOURS.convert(duration, this).

final var ret1 = TimeUnit.DAYS.toHours(1);
System.out.println(ret1); // 24

final var ret2 = TimeUnit.MINUTES.toHours(60 * 10);
System.out.println(ret2); // 10

long toMicros (long duration)

Equivalent to MICROSECONDS.convert(duration, this).

final var ret1 = TimeUnit.MILLISECONDS.toMicros(1);
System.out.println(ret1); // 1000

final var ret2 = TimeUnit.NANOSECONDS.toMicros(1000 * 50);
System.out.println(ret2); // 50

long toMillis (long duration)

Equivalent to MILLISECONDS.convert(duration, this).

final var ret1 = TimeUnit.SECONDS.toMillis(1);
System.out.println(ret1); // 1000

final var ret2 = TimeUnit.MICROSECONDS.toMillis(1000 * 50);
System.out.println(ret2); // 50

long toMinutes (long duration)

Equivalent to MINUTES.convert(duration, this).

final var ret1 = TimeUnit.HOURS.toMinutes(1);
System.out.println(ret1); // 60

final var ret2 = TimeUnit.SECONDS.toMinutes(60 * 150);
System.out.println(ret2); // 150

long toNanos (long duration)

Equivalent to NANOSECONDS.convert(duration, this).

final var ret1 = TimeUnit.MICROSECONDS.toNanos(1);
System.out.println(ret1); // 1000

final var ret2 = TimeUnit.MILLISECONDS.toNanos(5);
System.out.println(ret2); // 5000000

long toSeconds (long duration)

Equivalent to SECONDS.convert(duration, this).

final var ret1 = TimeUnit.MINUTES.toSeconds(1);
System.out.println(ret1); // 60

final var ret2 = TimeUnit.MILLISECONDS.toSeconds(1000 * 150);
System.out.println(ret2); // 150

static TimeUnit valueOf (String name)

Returns the enum constant of this class with the specified name.

final var ret1 = TimeUnit.valueOf("DAYS");
System.out.println(ret1); // DAYS

final var ret2 = TimeUnit.valueOf("SECONDS");
System.out.println(ret2); // SECONDS

static TimeUnit[] values ()

Returns an array containing the constants of this enum class, in the order they are declared.

for (final var value : TimeUnit.values()) {
    System.out.println(value);
}

// Result
// ↓
//NANOSECONDS
//MICROSECONDS
//MILLISECONDS
//SECONDS
//MINUTES
//HOURS
//DAYS

Methods declared in Enum

clone, compareTo, describeConstable, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Please see the link below.


Related posts

To top of page