Skip to content

Instantly share code, notes, and snippets.

@bristermitten
Created February 29, 2020 15:24
Show Gist options
  • Save bristermitten/54471e133f856091000a9e557bc5add7 to your computer and use it in GitHub Desktop.
Save bristermitten/54471e133f856091000a9e557bc5add7 to your computer and use it in GitHub Desktop.
Converts a time in seconds to a pretty string
/**
* 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