Does anyone know of a Java library that can pretty print a number in milliseconds in the same way that C# does?
E.g., 123456 ms as a long would be printed as 4d1h3m5
org.threeten.extra.AmountFormats.wordBased
The ThreeTen-Extra project, which is maintained by Stephen Colebourne, the author of JSR 310, java.time, and Joda-Time, has an AmountFormats class which works with the standard Java 8 date time classes. It's fairly verbose though, with no option for more compact output.
Duration d = Duration.ofMinutes(1).plusSeconds(9).plusMillis(86);
System.out.println(AmountFormats.wordBased(d, Locale.getDefault()));
1 minute, 9 seconds and 86 milliseconds
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
.
Java 9+
Duration d1 = Duration.ofDays(0);
d1 = d1.plusHours(47);
d1 = d1.plusMinutes(124);
d1 = d1.plusSeconds(124);
System.out.println(String.format("%s d %sh %sm %ss",
d1.toDaysPart(),
d1.toHoursPart(),
d1.toMinutesPart(),
d1.toSecondsPart()));
2 d 1h 6m 4s
Here's how you can do it using pure JDK code:
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
long diffTime = 215081000L;
Duration duration = DatatypeFactory.newInstance().newDuration(diffTime);
System.out.printf("%02d:%02d:%02d", duration.getDays() * 24 + duration.getHours(), duration.getMinutes(), duration.getSeconds());
I realize this might not fit your use case exactly, but PrettyTime might be useful here.
PrettyTime p = new PrettyTime();
System.out.println(p.format(new Date()));
//prints: “right now”
System.out.println(p.format(new Date(1000*60*10)));
//prints: “10 minutes from now”
With Java 8 you can also use the toString() method of java.time.Duration to format it without external libraries using ISO 8601 seconds based representation such as PT8H6M12.345S.