TimeParser { public static long parseDuration(String durationStr) { Preconditions.checkArgument(!Strings.isNullOrEmpty(durationStr)); durationStr = durationStr.trim().toLowerCase(); String value = durationStr.substring(0, durationStr.length() - 1); long parsedValue; try { parsedValue = Long.parseLong(value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("Error parsing the duration string %s. Cannot parse %s as a long", durationStr, value)); } char lastChar = durationStr.charAt(durationStr.length() - 1); switch (lastChar) { case 's': return TimeUnit.SECONDS.toMillis(parsedValue); case 'm': return TimeUnit.MINUTES.toMillis(parsedValue); case 'h': return TimeUnit.HOURS.toMillis(parsedValue); case 'd': return TimeUnit.DAYS.toMillis(parsedValue); } throw new IllegalArgumentException(String.format("Time unit not supported: %s", lastChar)); } TimeParser(long runtime); long parseRuntime(String str); static long parseDuration(String durationStr);  }
@Test public void testDurationParse() { Assert.assertEquals(TimeUnit.MINUTES.toMillis(5), TimeParser.parseDuration("5m")); Assert.assertEquals(TimeUnit.SECONDS.toMillis(5), TimeParser.parseDuration("5s")); Assert.assertEquals(TimeUnit.HOURS.toMillis(5), TimeParser.parseDuration("5h")); Assert.assertEquals(TimeUnit.DAYS.toMillis(5), TimeParser.parseDuration("5d")); Assert.assertEquals(TimeUnit.DAYS.toMillis(5), TimeParser.parseDuration("+5d")); Assert.assertEquals(0 - TimeUnit.DAYS.toMillis(5), TimeParser.parseDuration("-5d")); }