Duration { public static Duration parse(String duration) { String d = duration.trim(); if (!PATTERN.matcher(d).matches()) { throw new DurationFormatException( "Duration string " + duration + " doesn't match pattern " + PATTERN); } String u = PATTERN_NUMBER.matcher(d).replaceFirst(EMPTY); long v = Long.parseLong(PATTERN_UNIT.matcher(d).replaceFirst(EMPTY)); if (u.length() == 0) { } else if (u.equals(SECOND)) { v = v * 1000L; } else if (u.equals(MINUTE)) { v = v * 1000L * 60L; } else if (u.equals(HOUR)) { v = v * 1000L * 60L * 60L; } else if (u.equals(DAY)) { v = v * 1000L * 60L * 60L * 24L; } return new Duration(v); } Duration(long milliseconds); long getValue(); Date since(); Date since(Date date); static Duration parse(String duration);  }
@Test public void testParse() { assertEquals(4L, Duration.parse("4").getValue()); assertEquals(4 * 1000L, Duration.parse("4s").getValue()); assertEquals(4 * 60 * 1000L, Duration.parse("4m").getValue()); assertEquals(4 * 60 * 60 * 1000L, Duration.parse("4h").getValue()); assertEquals(4 * 60 * 60 * 1000L * 24L, Duration.parse("4d").getValue()); }
@Test(expected=DurationFormatException.class) public void testParseFail1() { Duration.parse("s"); }
@Test(expected=DurationFormatException.class) public void testParseFail2() { Duration.parse("x"); }
@Test(expected=DurationFormatException.class) public void testParseFail3() { Duration.parse("s0"); }