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 hoursHOURS
: 60 minutesMICROSECONDS
: one thousandth of a millisecondMILLISECONDS
: one thousandth of a secondMINUTES
: 60 secondsNANOSECONDS
: one thousandth of a microsecondSECONDS
: 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