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

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

    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

提交回复
热议问题