Created
March 24, 2012 20:26
-
-
Save bivas/2187493 to your computer and use it in GitHub Desktop.
Human Readable Duration
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
long now = System.currentTimeMillis(); | |
doSomeLongTask(); | |
long duration = System.currentTimeMillis() - now; |
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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It crashes with null exception at line 23 if for example are millis is passed 231 ms.