Skip to content
This repository has been archived by the owner on Apr 22, 2021. It is now read-only.

Commit

Permalink
Feature: add days and weeks support to human duration
Browse files Browse the repository at this point in the history
  • Loading branch information
luguina committed Jun 8, 2020
1 parent 0aa8f8b commit 5df4268
Showing 1 changed file with 32 additions and 12 deletions.
44 changes: 32 additions & 12 deletions src/com/sheepit/client/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,11 @@
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -182,24 +184,42 @@ public static long parseNumber(String in) {
}

public static String humanDuration(Date date) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
ZoneId zoneId = ZoneId.of("GMT");
LocalDateTime tempDate = LocalDateTime.ofInstant(date.toInstant(), zoneId);
LocalDateTime epoch = LocalDateTime.ofInstant(Instant.ofEpochSecond(0), zoneId);

int hours = (calendar.get(Calendar.DAY_OF_MONTH) - 1) * 24 + calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
long months = epoch.until(tempDate, ChronoUnit.MONTHS);
epoch = epoch.plusMonths(months);

String output = "";
long days = epoch.until(tempDate, ChronoUnit.DAYS);
epoch = epoch.plusDays(days);

long hours = epoch.until(tempDate, ChronoUnit.HOURS);
epoch = epoch.plusHours(hours);

long minutes = epoch.until(tempDate, ChronoUnit.MINUTES);
epoch = epoch.plusMinutes(minutes);

long seconds = epoch.until(tempDate, ChronoUnit.SECONDS);

StringBuilder output = new StringBuilder();
if (months > 0) {
output.append(String.format("%dmonth%s ", months, (months > 1 ? "s" : "")));
}
if (days > 0) {
output.append(String.format("%dday%s ", days, (days > 1 ? "s" : "")));
}
if (hours > 0) {
output += hours + "h ";
output.append(String.format("%dh ", hours));
}
if (minutes > 0) {
output += minutes + "min ";
output.append(String.format("%dmin ", minutes));
}
if (seconds > 0) {
output += seconds + "s";
output.append(String.format("%ds", seconds));
}
return output;

return output.toString().trim();
}

public static boolean noFreeSpaceOnDisk(String destination_) {
Expand Down

0 comments on commit 5df4268

Please sign in to comment.