sheepit-client icon indicating copy to clipboard operation
sheepit-client copied to clipboard

Feature: add days and weeks support to human duration

Open luguina opened this issue 4 years ago • 5 comments

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".

luguina avatar Jun 03 '20 14:06 luguina

Doesn't Java 8 have new Apis for working with time and dates, thus making parts of this pr obsolete?

intrigus avatar Jun 03 '20 16:06 intrigus

java 8 introduced java.time. java.util.Calendar and friends are now considered legacy.

MCOfficer avatar Jun 03 '20 18:06 MCOfficer

Why not java.time.Duration?

andylizi avatar Jun 05 '20 15:06 andylizi

Why not java.time.Duration?

Feel free to propose the code as you did with the OkHTTP and I'll review @andylizi.

luguina avatar Jun 06 '20 00:06 luguina

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.

andylizi avatar Jun 06 '20 04:06 andylizi