Created
May 13, 2020 19:06
-
-
Save JohnnyJayJay/5fdc95eaba4b244e00e8f03c8ead2419 to your computer and use it in GitHub Desktop.
util for simple duration formatting
This file contains hidden or 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
import java.time.Duration; | |
import java.util.Iterator; | |
import java.util.LinkedHashMap; | |
import java.util.Map; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* @author Johnny_JayJay (https://www.github.com/JohnnyJayJay) | |
*/ | |
public final class DurationFormatter { | |
private static final Map<TimeUnit, Integer> unitSizes = new LinkedHashMap<>(); | |
static { | |
int ms = 1; | |
int s = ms * 1000; | |
int min = s * 60; | |
int h = min * 60; | |
int d = h * 24; | |
unitSizes.put(TimeUnit.DAYS, d); | |
unitSizes.put(TimeUnit.HOURS, h); | |
unitSizes.put(TimeUnit.MINUTES, min); | |
unitSizes.put(TimeUnit.SECONDS, s); | |
unitSizes.put(TimeUnit.MILLISECONDS, ms); | |
} | |
private DurationFormatter() {} | |
public static String format(Duration duration, String formatString, TimeUnit biggestUnit) { | |
Iterator<TimeUnit> iterator = unitSizes.keySet().iterator(); | |
while (iterator.hasNext() && iterator.next() != biggestUnit); | |
if (!iterator.hasNext()) { | |
throw new IllegalArgumentException(); | |
} | |
TimeUnit current = biggestUnit; | |
long remainingMillis = duration.toMillis(); | |
String result = formatString; | |
do { | |
long unitSize = unitSizes.get(current); | |
long amount = remainingMillis / unitSize; | |
result = result.replace("{" + current.name().toLowerCase() + "}", String.valueOf(amount)); | |
remainingMillis %= unitSize; | |
current = iterator.next(); | |
} while (iterator.hasNext()); | |
return result; | |
} | |
} |
Weil diese Reihenfolge wichtig ist. Abgesehen davon wäre es hier sowieso relativ egal, da das eine einmalige Map ist
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 12: Warum eine LinkedHashMap und keine EnumMap?
(Was macht die LinkedHashMap besser in dieser Anwendung?)