Created
February 29, 2020 15:24
-
-
Save bristermitten/54471e133f856091000a9e557bc5add7 to your computer and use it in GitHub Desktop.
Converts a time in seconds to a pretty string
This file contains hidden or 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 second time to a "pretty" string | |
* Credit: https://stackoverflow.com/a/7663966 (modified for correct English if there's only 1 unit) | |
* @param seconds the time | |
* @return a pretty string | |
*/ | |
public static String getDurationBreakdown(long seconds) { | |
if (seconds < 0) { | |
throw new IllegalArgumentException("Duration must be greater than zero!"); | |
} | |
long days = TimeUnit.SECONDS.toDays(seconds); | |
seconds -= TimeUnit.DAYS.toSeconds(days); | |
long hours = TimeUnit.SECONDS.toHours(seconds); | |
seconds -= TimeUnit.HOURS.toSeconds(hours); | |
long minutes = TimeUnit.SECONDS.toMinutes(seconds); | |
seconds -= TimeUnit.MINUTES.toSeconds(minutes); | |
StringBuilder sb = new StringBuilder(64); | |
if (days != 0) { | |
sb.append(days); | |
sb.append(" Days "); | |
} | |
if (hours != 0) { | |
sb.append(hours); | |
sb.append(" Hours "); | |
} | |
if (minutes != 0) { | |
sb.append(minutes); | |
sb.append(" Minute"); | |
if (minutes != 1) { | |
sb.append("s"); | |
} | |
sb.append(' '); | |
} | |
if (seconds != 0) { | |
sb.append(seconds); | |
sb.append(" Second"); | |
if (seconds != 1) | |
sb.append("s"); | |
} | |
return sb.toString().trim(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment