TimeDurationFormatter { public String format(long amount, TimeUnit unit) { long nanos = unit.toNanos(amount); TimeUnit outputUnit = TimeUnit.NANOSECONDS; for (TimeUnit u : UNITS) { if (u.convert(nanos, TimeUnit.NANOSECONDS) >= this.threshold) { outputUnit = u; break; } } double convertedToUnit = ((double) nanos) / (TimeUnit.NANOSECONDS.convert(1, outputUnit)); return String.format(this.locale, "%.4g %s", convertedToUnit, this.allowNonAscii ? DISPLAYUNIT.get(outputUnit) : DISPLAYUNIT_ASCII.get(outputUnit)); } TimeDurationFormatter(Locale locale, int threshold, boolean allowNonAscii); static TimeDurationFormatter forLogging(); String format(long amount, TimeUnit unit);  }
@Test public void defaultFormatter() { assertEquals("2.000 d", df.format(2, TimeUnit.DAYS)); assertEquals("24.00 h", df.format(1, TimeUnit.DAYS)); assertEquals("10.50 d", df.format(24 * 10 + 12, TimeUnit.HOURS)); assertEquals("2.500 h", df.format(150, TimeUnit.MINUTES)); assertEquals("10.00 min", df.format(10, TimeUnit.MINUTES)); assertEquals("1234 us", df.format(1234, TimeUnit.MICROSECONDS)); assertEquals("1234 ns", df.format(1234, TimeUnit.NANOSECONDS)); }
@Test public void uniFormatterWithOneThreshold() { assertEquals("2,000 d", dfu.format(2, TimeUnit.DAYS)); assertEquals("1,000 d", dfu.format(1, TimeUnit.DAYS)); assertEquals("10,50 d", dfu.format(24 * 10 + 12, TimeUnit.HOURS)); assertEquals("2,500 h", dfu.format(150, TimeUnit.MINUTES)); assertEquals("10,00 min", dfu.format(10, TimeUnit.MINUTES)); assertEquals("1,234 ms", dfu.format(1234, TimeUnit.MICROSECONDS)); assertEquals("1,234 \u00b5s", dfu.format(1234, TimeUnit.NANOSECONDS)); }