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 4d1h3m5s.
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 4d1h3m5s.
Here's how you can do it using pure JDK code:
Java 9
2 d 1h 6m 4s
An alternative to the builder-approach of Joda-Time would be a pattern-based solution. This is offered by my library Time4J. Example using the class Duration.Formatter (added some spaces for more readability - removing the spaces will yield the wished C#-style):
Another way is using the class
net.time4j.PrettyTime
(which is also good for localized output and printing relative times):I've built a simple solution, using Java 8's
Duration.toString()
and a bit of regex:The result will look like:
If you don't want spaces between, just remove
replaceAll
.I realize this might not fit your use case exactly, but PrettyTime might be useful here.
JodaTime has a
Period
class that can represent such quantities, and can be rendered (viaIsoPeriodFormat
) in ISO8601 format, e.g.PT4D1H3M5S
, e.g.If that format isn't the one you want, then
PeriodFormatterBuilder
lets you assemble arbitrary layouts, including your C#-style4d1h3m5s
.