UnitConverter { public static long toDurationMillis(String duration) { Matcher matcher = NUMBER_AND_UNIT.matcher(duration); if (!matcher.matches()) { throw new IllegalArgumentException("malformed duration string: " + duration); } long number = Long.parseLong(matcher.group(1)); String unitStr = matcher.group(2); if (unitStr == null) { return number; } char unit = unitStr.toLowerCase().charAt(0); switch (unit) { case 's': return number * MILLIS_PER_SECOND; case 'm': if (unitStr.length() >= 2 && unitStr.charAt(1) == 's') { return number; } return number * MILLIS_PER_MINUTE; case 'h': return number * MILLIS_PER_HOUR; case 'd': return number * MILLIS_PER_DAY; default: throw new IllegalArgumentException("unknown time unit :" + unit); } }  static long toDurationMillis(String duration); static long toBytes(String size); static String toSizeUnit(Long bytes, int scale); static String toTimeUnit(long millis, int scale); static String toTimeWithMinorUnit(long millis);  }
@Test public void convertDurationMillis() { assertThat(UnitConverter.toDurationMillis("12345")).isEqualTo(12345); assertThat(UnitConverter.toDurationMillis("12S")).isEqualTo(12000); assertThat(UnitConverter.toDurationMillis("12s")).isEqualTo(12000); assertThat(UnitConverter.toDurationMillis("12ms")).isEqualTo(12); assertThat(UnitConverter.toDurationMillis("12m")).isEqualTo(12 * 60 * 1000); assertThat(UnitConverter.toDurationMillis("12h")).isEqualTo(12l * 60 * 60 * 1000); assertThat(UnitConverter.toDurationMillis("12d")).isEqualTo(12l * 24 * 60 * 60 * 1000); try { assertThat(UnitConverter.toDurationMillis("12a")).isEqualTo(12 * 60 * 1000); fail("should fail"); } catch (Throwable t) { assertThat(t).isInstanceOf(IllegalArgumentException.class); } try { assertThat(UnitConverter.toDurationMillis("a12")).isEqualTo(12 * 60 * 1000); fail("should fail"); } catch (Throwable t) { assertThat(t).isInstanceOf(IllegalArgumentException.class); } }