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.
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.
On
java.time.DurationUse 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.
Use DurationFormatUtils.formatDurationWords instead:
The result will be:
X days Y hours Z minuteswithout leading or trailing zero elementsDetail: https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/time/DurationFormatUtils.html#formatDurationWords-long-boolean-boolean-