Here's one approach, using TreeMap
. It looks up your number of milliseconds in a pre-populated map, finds the appropriate entry and does the division.
Just create one of these objects, and call the format
method as many times as you need to.
Note that it's not quite right for negative arguments to format
- but you might want to put your own logic in around that, for example, to throw some kind of exception.
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
public class TimeFormatter {
private NavigableMap<Long,String> timeUnits = new TreeMap<>();
public TimeFormatter() {
timeUnits.put(Long.MIN_VALUE, " is not a valid argument");
timeUnits.put(1L, " milliseconds");
timeUnits.put(1000L, " seconds");
timeUnits.put(60 * 1000L, " minutes");
timeUnits.put(60 * 60 * 1000L, " hours");
timeUnits.put(24 * 60 * 60 * 1000L, " days");
timeUnits.put(365 * 24 * 60 * 60 * 1000L, " years");
timeUnits.put(1000000L * 365 * 24 * 60 * 60 * 1000L, " million years");
timeUnits.put(1000000000L * 365 * 24 * 60 * 60 * 1000L, " billion years");
}
public String format(long milliseconds) {
Map.Entry<Long,String> unitBelow = timeUnits.floorEntry(milliseconds);
return milliseconds / unitBelow.getKey() + unitBelow.getValue();
}
}