Re: How to convert x (elapsed) milliseconds into human-readable
format "..d..h..m..s" ?
On Sun, 13 Sep 2009, Ulf Meinhardt wrote:
Assume I have a number of milliseconds.
How can I convert this value into a more human-readable format
with days, hours, minutes and seconds like:
56d17h23m56s
If the number of days is equals to 0 then the "d" part should be omitted.
I don't think there's anything in the standard library that will do this -
my gut feeling is that you can't twist Calendar into doing this, but i
could very well be wrong.
Here's how i'd do it, with a nice fallthrough switch statement:
public class UlfTime {
public static void main(String... args) {
for (String arg: args) {
long time = Long.parseLong(arg);
String timeStr = format(time);
System.out.println(timeStr);
}
}
private static enum TimeUnit {MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS}
public static String format(long time) {
if (time < 0L) throw new IllegalArgumentException("negative time: " + time);
TimeUnit largest;
int ms = (int)(time % 1000);
largest = TimeUnit.MILLISECONDS;
time /= 1000;
int s = (int)(time % 60);
if (s != 0) largest = TimeUnit.SECONDS;
time /= 60;
int m = (int)(time % 60);
if (m != 0) largest = TimeUnit.MINUTES;
time /= 60;
int h = (int)(time % 24);
if (h != 0) largest = TimeUnit.HOURS;
time /= 24;
long d = time;
if (d != 0) largest = TimeUnit.DAYS;
StringBuilder sb = new StringBuilder();
switch (largest) {
case DAYS: sb.append(d); sb.append("d");
case HOURS: sb.append(h); sb.append("h");
case MINUTES: sb.append(m); sb.append("m");
case SECONDS: sb.append(s); sb.append("s");
case MILLISECONDS: sb.append(ms); sb.append("ms");
}
return sb.toString();
}
}
This could almost certainly be expressed more compactly with a little
ingenuity.
tom
--
Also, a 'dark future where there is only war!' ... have you seen the
news lately? -- applez