Created
December 25, 2022 10:27
-
-
Save hamza-cskn/175c6f948fe87b3565fd45a8a41b0563 to your computer and use it in GitHub Desktop.
Formats durations to relative times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
formatRelativeDuration(getRelativeDuration(new Date(), true))
-> 400 days 12 hours 13 minutes 14 secondsformatRelativeDuration(getRelativeDuration(new Date(), false))
-> 400 days