javamillisecondshuman-readable

What's the easiest way to convert milliseconds to readable String in Java Spring


How to convert during(milliseconds) from long to readable String in Java, such as 5 minutes and 2 seconds or 2 hours if no trailing minutes or seconds?

I have tried TimeUtils, but it still requires a little script to concatenate strings.


Solution

  • Use DurationFormatUtils.formatDurationWords instead:

    import org.apache.commons.lang3.time.DurationFormatUtils;
    
    ...
    DurationFormatUtils.formatDurationWords(milliseconds, true, true);
    ...
    

    The result will be: X days Y hours Z minutes without leading or trailing zero elements

    Detail: https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/time/DurationFormatUtils.html#formatDurationWords-long-boolean-boolean-