sheepit-client
sheepit-client copied to clipboard
Feature: add days and weeks support to human duration
Some counters (ie the Session duration) can run for more than 24h. The existing method has a maximum resolution of hours, generating values like "175h 39m 4s". While is not an error, is not visually aesthetic.
The PR extends the maximum resolution to weeks, producing values like "3weeks 4days 6h 45m 9s" instead of "606h 45m 9s".
Doesn't Java 8 have new Apis for working with time and dates, thus making parts of this pr obsolete?
java 8 introduced java.time
. java.util.Calendar
and friends are now considered legacy.
Why not java.time.Duration
?
Why not
java.time.Duration
?
Feel free to propose the code as you did with the OkHTTP and I'll review @andylizi.
public static String humanDuration(Date date) {
Duration duration = Duration.between(date.toInstant(), Instant.now()).abs();
long days = duration.toDays();
duration = duration.minusDays(days);
long months = days / 31;
days %= 31;
long hours = duration.toHours();
duration = duration.minusHours(hours);
long minutes = duration.toMinutes();
duration = duration.minusMinutes(minutes);
long seconds = duration.getSeconds();
StringBuilder b = new StringBuilder();
if (months > 0) {
b.append(months).append("month");
if (months > 1) b.append('s');
b.append(' ');
}
if (days > 0) {
b.append(days).append("day");
if (days > 1) b.append('s');
b.append(' ');
}
if (hours > 0) b.append(hours).append("h ");
if (minutes > 0) b.append(minutes).append("m ");
if (seconds > 0) b.append(seconds).append('s');
return b.toString().trim();
}
This isn't as clean and elegant as I'd like, as the to**Parts()
methods weren't added until Java 9.