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

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-28 08:24

    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()); 
    
    0 讨论(0)
  • 2020-11-28 08:28

    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”
    
    0 讨论(0)
  • 2020-11-28 08:29

    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.

    0 讨论(0)
提交回复
热议问题