LiberalDurationParser { public static Optional<Duration> parse(String text) { Matcher matcher = PATTERN.matcher(text); if (matcher.find()) { long value = Long.parseLong(matcher.group(1)); String unit = matcher.group(2).toUpperCase(); if ( ! unit.endsWith("S") ) { unit = unit + "S"; } ChronoUnit chronoUnit = ChronoUnit.valueOf(unit); switch (unit) { case "WEEKS": value *= 7; chronoUnit = ChronoUnit.DAYS; break; case "MONTHS": value *= 30; chronoUnit = ChronoUnit.DAYS; break; case "YEARS": value *= 365; chronoUnit = ChronoUnit.DAYS; break; } try { Duration duration = Duration.of(value, chronoUnit); return Optional.of(duration); } catch (UnsupportedTemporalTypeException e) { throw new UnsupportedTemporalTypeException("Unable to parse: " + text, e); } } return Optional.empty(); }  static Optional<Duration> parse(String text);  }
@Test public void parse() throws Exception { assertEquals("Optional[PT1M]", LiberalDurationParser.parse("1minute").toString()); assertEquals("Optional[PT1M]", LiberalDurationParser.parse("1minutes").toString()); assertEquals("Optional[PT2M]", LiberalDurationParser.parse("2minutes").toString()); assertEquals("Optional[PT24H]", LiberalDurationParser.parse("1day").toString()); assertEquals("Optional[PT48H]", LiberalDurationParser.parse("2day").toString()); assertEquals("Optional[PT48H]", LiberalDurationParser.parse("2days").toString()); assertEquals("Optional[PT168H]", LiberalDurationParser.parse("1weeks").toString()); assertEquals("Optional[PT720H]", LiberalDurationParser.parse("1months").toString()); assertEquals("Optional[PT8760H]", LiberalDurationParser.parse("1year").toString()); ArrayList<ChronoUnit> chronoUnits = Lists.newArrayList(MILLIS, SECONDS, MINUTES, HOURS, DAYS, WEEKS, MONTHS, YEARS); for (ChronoUnit chronoUnit : chronoUnits) { for (long value = 0; value < 40; value++) { long millis = value * toUnitMillis(chronoUnit); Duration expected = Duration.of(millis, MILLIS); String text = String.format("%s%s", value, chronoUnit.toString().toLowerCase() ); test(expected, text); test(expected, toSingular(text)); test(expected, text.toUpperCase()); test(expected, toSingular(text).toUpperCase()); } } }