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

前端 未结 11 900
盖世英雄少女心
盖世英雄少女心 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:14

    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

提交回复
热议问题