How to Convert Between Millis, Minutes, Hours, Days (and more) in Java

How can we convert from days to milliseconds? What about hours to milliseconds? Or milliseconds to days? Or minutes to nanoseconds?

All of this is possible with the TimeUnit class.

Using TimeUnit to convert duration

TimeUnit is a Java class that allows us to convert from one duration to another.

The supported durations include the following enum constants:

  • DAYS: 24 hours
  • HOURS: 60 minutes
  • MICROSECONDS: one thousandth of a millisecond
  • MILLISECONDS: one thousandth of a second
  • MINUTES: 60 seconds
  • NANOSECONDS: one thousandth of a microsecond
  • SECONDS: 1 second

Usage of TimeUnit

Here are some example usages of TimeUnit to convert between durations.

TimeUnit.DAYS.toMinutes(10);        // 10 days to minutes
TimeUnit.MINUTES.toHours(10);       // 10 minutes to hours
TimeUnit.HOURS.toSeconds(10);       // 10 hours to seconds
TimeUnit.SECONDS.toMillis(10);      // 10 seconds to milliseconds
TimeUnit.MILLISECONDS.toMicros(10); // 10 milliseconds to microseconds
TimeUnit.MICROSECONDS.toNanos(10);  // 10 microseconds to nanoseconds

The supported methods to convert between durations include the following:

  • long toDays‚Äč(long duration)
  • long toHours‚Äč(long duration)
  • long toMicros‚Äč(long duration)
  • long toMillis‚Äč(long duration)
  • long toMinutes‚Äč(long duration)
  • long toNanos‚Äč(long duration)
  • long toSeconds‚Äč(long duration)

Usage of TimeUnit::convert

All of these methods are equivalent to using TimeUnit::convert.

The above methods can be rewritten with convert().

TimeUnit.MINUTES.convert(10, TimeUnit.DAYS);              // 10 days to minutes
TimeUnit.HOURS.convert(10, TimeUnit.MINUTES);             // 10 minutes to hours
TimeUnit.SECONDS.convert(10, TimeUnit.HOURS);             // 10 hours to seconds
TimeUnit.MILLISECONDS.convert(10, TimeUnit.SECONDS);      // 10 seconds to milliseconds
TimeUnit.MICROSECONDS.convert(10, TimeUnit.MILLISECONDS); // 10 milliseconds to microseconds
TimeUnit.NANOSECONDS.convert(10, TimeUnit.MICROSECONDS);  // 10 microseconds to nanoseconds