public static String formatMillisecondsToConventional ( long duration , int unitCount ) { if ( unitCount <= 0 ) { unitCount = 5 ; } if ( duration == 0 ) { return "0ms" ; } StringBuffer sb = new StringBuffer ( ) ; if ( duration < 0 ) { sb . append ( "-" ) ; } long absTime = Math . abs ( duration ) ; long [ ] thresholds = { DAY_IN_MS , HOUR_IN_MS , 60000 , 1000 , 1 } ; String [ ] units = { "d" , "h" , "m" , "s" , "ms" } ; for ( int i = 0 ; i < thresholds . length ; i ++ ) { if ( absTime >= thresholds [ i ] ) { sb . append ( absTime / thresholds [ i ] + units [ i ] ) ; absTime = absTime % thresholds [ i ] ; unitCount -- ; } if ( unitCount == 0 ) { break ; } } return sb . toString ( ) ; }
Convert milliseconds value to a human - readable duration of mixed units using units no larger than days . For example 5d12h13m12s113ms or 19h51m .