Skip to content

Instantly share code, notes, and snippets.

@bivas
Created March 24, 2012 20:26
Show Gist options
  • Save bivas/2187493 to your computer and use it in GitHub Desktop.
Save bivas/2187493 to your computer and use it in GitHub Desktop.
Human Readable Duration
long now = System.currentTimeMillis();
doSomeLongTask();
long duration = System.currentTimeMillis() - now;
package com.example.commons.humanreadable.utils;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.WordUtils;
public final class HumanReadableUtils {
private static final List<TimeUnit> timeUnits = Arrays.asList(TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.MINUTES,
TimeUnit.SECONDS);
public static String toHumanReadableDuration(final long millis) {
final StringBuilder builder = new StringBuilder();
long acc = millis;
for (final TimeUnit timeUnit : timeUnits) {
final long convert = timeUnit.convert(acc, TimeUnit.MILLISECONDS);
if (convert > 0) {
builder.append(convert).append(' ').append(WordUtils.capitalizeFully(timeUnit.name())).append(", ");
acc -= TimeUnit.MILLISECONDS.convert(convert, timeUnit);
}
}
return builder.substring(0, builder.length() - 2);
}
}
@lapkritinis
Copy link

It crashes with null exception at line 23 if for example are millis is passed 231 ms.

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