-
-
Save jwne/bb6ab3a44c2cf2ac990f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert a millisecond duration to a string format | |
* | |
* @param millis A duration to convert to a string form. | |
* @return A string of the form "X Days Y Hours Z Minutes A Seconds". | |
*/ | |
public static String getDurationBreakdown( long millis ) | |
{ | |
if ( millis < 1000 ) return "a short amount of time!"; | |
long days = TimeUnit.MILLISECONDS.toDays( millis ); | |
millis -= TimeUnit.DAYS.toMillis( days ); | |
long hours = TimeUnit.MILLISECONDS.toHours( millis ); | |
millis -= TimeUnit.HOURS.toMillis( hours ); | |
long minutes = TimeUnit.MILLISECONDS.toMinutes( millis ); | |
millis -= TimeUnit.MINUTES.toMillis( minutes ); | |
long seconds = TimeUnit.MILLISECONDS.toSeconds( millis ); | |
StringBuilder sb = new StringBuilder(); | |
if ( days > 0 ) { | |
sb.append( days ).append( " day" ); | |
if ( days > 1 ) sb.append( "s" ); | |
} | |
if ( hours > 0 ) { | |
if ( days > 0 ) sb.append( ", " ); | |
sb.append( hours ).append( " hour" ); | |
if ( hours > 1 ) sb.append( "s" ); | |
} | |
if ( minutes > 0 ) { | |
if ( hours > 0 || days > 0 ) sb.append( ", " ); | |
sb.append( minutes ).append( " minute" ); | |
if ( minutes > 1 ) sb.append( "s" ); | |
} | |
if ( seconds > 0 ) { | |
if ( minutes > 0 || hours > 0 || days > 0 ) sb.append( ", " ); | |
sb.append( seconds ).append( " second" ); | |
if ( seconds > 1 ) sb.append( "s" ); | |
} | |
return ( sb.append( "." ).toString() ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment