Skip to content

Instantly share code, notes, and snippets.

@hamza-cskn
Created December 25, 2022 10:27
Show Gist options
  • Save hamza-cskn/175c6f948fe87b3565fd45a8a41b0563 to your computer and use it in GitHub Desktop.
Save hamza-cskn/175c6f948fe87b3565fd45a8a41b0563 to your computer and use it in GitHub Desktop.
Formats durations to relative times
public static Duration getRelativeDuration(Date date) {
return Duration.ofMillis(Objects.requireNonNull(date).toInstant().toEpochMilli() - System.currentTimeMillis());
}
public static String formatRelativeDuration(Duration duration, boolean verbose) {
if (duration.isZero()) return "now";
String direction = duration.isNegative() ? "ago" : "later";
duration = duration.abs();
StringBuilder builder = new StringBuilder();
if (!applyTimeFormat(builder, duration.toDaysPart(), "day") || verbose)
if (!applyTimeFormat(builder, duration.toHoursPart(), "hour") || verbose)
if (!applyTimeFormat(builder, duration.toMinutesPart(), "minute") || verbose)
applyTimeFormat(builder, duration.toSecondsPart(), "second");
builder.append(" ").append(direction);
return builder.toString();
}
private static boolean applyTimeFormat(StringBuilder builder, long amount, String timeType) {
if (amount <= 0) return false;
if (!builder.isEmpty()) builder.append(" ");
builder.append(amount).append(" ").append(timeType);
if (amount != 1) builder.append("s");
return true;
}
@hamza-cskn
Copy link
Author

formatRelativeDuration(getRelativeDuration(new Date(), true)) -> 400 days 12 hours 13 minutes 14 seconds
formatRelativeDuration(getRelativeDuration(new Date(), false)) -> 400 days

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment