1

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.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Alan 34e9
  • 31
  • 4
  • There isn't anything for this in the main Java libraries, so this would probably be asking for a library -- which might be closed. (Note also that this is something sensitive to the languages used by the consumers.) – Louis Wasserman Nov 08 '22 at 23:57
  • You might have a look at java.time.Duration: https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html – j_b Nov 09 '22 at 00:01

2 Answers2

2

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-

Alan 34e9
  • 31
  • 4
2

java.time.Duration

Use Duration to represent a span of time not attached to the timeline, on a scale of hours-minutes-seconds.

Duration d = Duration.parse( "PT5M2S" );

Parse your count of milliseconds as a Duration.

Duration d = Duration.ofMillis( myMillis ) ;

You can manipulate the standard ISO 8601 output from the Duration#toString.

String output =
        d
                .toString()
                .replace( "PT" , "" )
                .replace( "H" , " hours " )
                .replace( "M" , " minutes " )
                .replace( "S" , " seconds " )
                .stripTrailing();

output = 5 minutes 2 seconds

If you want to get more fancy, such as using singular for a value of one, use the Duration#to…Part methods.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Great answer! I recommend using [`String#trim`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#trim()) which has been available since the beginning. [`String#stripTrailing`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#stripTrailing()) was introduced with Java 11. – Arvind Kumar Avinash Nov 16 '22 at 10:38