Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

TimeUnit: fixed units of elapsed time

`TimeUnit` provides seven units from nanoseconds to days. Choose the unit that matches an amount, or convert different amounts to a common unit.

Version: Java SE 21

Syntax

import java.util.concurrent.TimeUnit;

long minutesPerHour = TimeUnit.MINUTES.convert(1L, TimeUnit.HOURS);
long minutesPerDay = TimeUnit.MINUTES.convert(1L, TimeUnit.DAYS);

java.util.concurrent.TimeUnit is an enum for fixed units of elapsed time. From finest to coarsest, its constants are NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, and DAYS.

A constant specifies the unit, not the amount: 1L with HOURS means one hour, while 1L with DAYS means one day. In TimeUnit, a day is always 24 hours. It is not a calendar day, which can have a different length when clocks change.

To express durations in a common unit, call targetUnit.convert(amount, sourceUnit). Call the method on the target unit and pass the source unit as the second argument. Converting to a coarser unit discards the fractional part: TimeUnit.HOURS.convert(90L, TimeUnit.MINUTES) returns 1.

Examples

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        long minutesPerHour = TimeUnit.MINUTES.convert(1L, TimeUnit.HOURS);
        long minutesPerDay = TimeUnit.MINUTES.convert(1L, TimeUnit.DAYS);

        System.out.println(minutesPerHour);
        System.out.println(minutesPerDay);
    }
}

Result

60
1440

Both conversions return a count of minutes. The program prints `60` for one hour and `1440` for one day.

Related lessons

  • Java · Lesson 41 · Advanced · Version: 2

Sources