How can I “pretty print” a Duration in Java?

前端 未结 11 915
盖世英雄少女心
盖世英雄少女心 2020-11-28 07:45

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

11条回答
  •  天命终不由人
    2020-11-28 08:20

    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.

提交回复
热议问题