Durations { public static String formatDuration(Duration duration) { long d = duration.toDays(); long h = duration.minusDays(d).toHours(); long m = duration.minusDays(d).minusHours(h).toMinutes(); long s = duration.minusDays(d).minusHours(h).minusMinutes(m).getSeconds(); return Stream.of( d == 0 ? null : d + "d", h == 0 ? null : h + "h", m == 0 ? null : m + "m", s == 0 ? null : s + "s") .filter(v -> v != null) .collect(Collectors.joining(" ")); }  static Duration parseDuration(CharSequence text); static String formatDuration(Duration duration);  }
@Test public void testFormatDuration() throws Exception { assertThat(formatDuration(parseDuration("17s")), is("17s")); assertThat(formatDuration(parseDuration("17S")), is("17s")); assertThat(formatDuration(parseDuration(" 17 s ")), is("17s")); assertThat(formatDuration(parseDuration("13m17s")), is("13m 17s")); assertThat(formatDuration(parseDuration(" 13 m 17 s ")), is("13m 17s")); assertThat(formatDuration(parseDuration(" 13 m 17 s ")), is("13m 17s")); assertThat(formatDuration(parseDuration("13M17S")), is("13m 17s")); assertThat(formatDuration(parseDuration(" 13 M 17 S ")), is("13m 17s")); assertThat(formatDuration(parseDuration(" 13 m 17 s ")), is("13m 17s")); assertThat(formatDuration(parseDuration("21h13m17s")), is("21h 13m 17s")); assertThat(formatDuration(parseDuration(" 21h 13m 17s ")), is("21h 13m 17s")); assertThat(formatDuration(parseDuration("21H13M17S")), is("21h 13m 17s")); assertThat(formatDuration(parseDuration(" 21 H 13 M 17 S ")), is("21h 13m 17s")); assertThat(formatDuration(parseDuration("3d21h13m17s")), is("3d 21h 13m 17s")); assertThat(formatDuration(parseDuration("3d 21h 13m 17s ")), is("3d 21h 13m 17s")); assertThat(formatDuration(parseDuration("3D21H13M17S")), is("3d 21h 13m 17s")); assertThat(formatDuration(parseDuration("3 D 21 H 13 M 17 S ")), is("3d 21h 13m 17s")); }