views:

70

answers:

2

Hi folks,

Does anyone know of a java library that can pretty print a number in milli seconds in the same way that c# does?

E.g. 123456 ms as a long would be printed as 4d1h3m5s

(might not be accurate , but you see hopefully what I'm getting at!!)

-ace

+2  A: 

JodaTime has a Period class that can represent such quantities, and can be rendered (via IsoPeriodFormat) in ISO8601 format, e.g. PT4D1H3M5S, e.g.

Period period = new Period(millis);
String formatted = ISOPeriodFormat.standard().print(period);

If that format isn't the one you want, then PeriodFormatterBuilder lets you assemble arbitrary layouts, including your C#-style 4d1h3m5s.

skaffman
+3  A: 

Joda Time has a pretty good way to do this using a PeriodFormatterBuilder.

e.g.

//import org.joda.time.format.PeriodFormatter;
//import org.joda.time.format.PeriodFormatterBuilder;
//import org.joda.time.Duration;

Duration duration = new Duration(123456); // in milliseconds
PeriodFormatter formatter = new PeriodFormatterBuilder()
     .appendDays()
     .appendSuffix("d")
     .appendHours()
     .appendSuffix("h")
     .appendMinutes()
     .appendSuffix("m")
     .appendSeconds()
     .appendSuffix("s")
     .toFormatter();
String formatted = formatter.print(duration.toPeriod());
System.out.println(formatted);
Rob Hruska
Many thanks - I had a suspicion something like this was in jodatime, just couldn't find it!
phatmanace