Get Time Unit in Java Using TimeUnit

This article shows how to get easily time units from a given value. This can be done using static methods exposed by java.util.concurrent.TimeUnit class.

For example, starting from seconds you can get days, hours and minutes in this way:

int day = (int)TimeUnit.SECONDS.toDays(seconds);        
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);

The following code shows how to get time units starting from:

int day = (int)TimeUnit.MINUTES.toDays(min);        
long hours = TimeUnit.MINUTES.toHours(min) - (day *24);
long minute = TimeUnit.MINUTES.toMinutes(min) - (TimeUnit.MINUTES.toHours(min)* 60);

If you want to learn more retro games news, read our magazine and subscribe to our newsletter.