Skip to content

Instantly share code, notes, and snippets.

@dim-s
Created February 21, 2019 11:59
Show Gist options
  • Save dim-s/941a02ef37a585c66f71850b6bece3b4 to your computer and use it in GitHub Desktop.
Save dim-s/941a02ef37a585c66f71850b6bece3b4 to your computer and use it in GitHub Desktop.
public class Timer {
public static long parsePeriod(String period) {
if (period == null || period.trim().isEmpty()) {
throw new IllegalArgumentException("Invalid period - '" + period + "', is empty");
}
period = period.trim();
String[] split = period.split(" ");
long value = 0;
Set<Character> types = new HashSet<>();
for (String one : split) {
if (one.trim().isEmpty()) {
continue;
}
one = one.trim();
char t = one.charAt(one.length() - 1);
int k = 1;
switch (Character.toLowerCase(t)) {
case 's': k = 1000; break;
case 'm': k = 1000 * 60; break;
case 'h': k = 1000 * 60 * 60; break;
case 'd': k = 1000 * 60 * 60 * 24; break;
default:
if (!Character.isDigit(t)) {
throw new IllegalArgumentException("Invalid period - '" + period + "', at '" + one + "'");
}
}
String num = one;
if (Character.isDigit(t)) {
} else {
if (!types.add(t)) {
throw new IllegalArgumentException("Invalid period - '" + period + "', at '" + one + "' that duplicates '" + t + "'");
}
num = one.substring(0, one.length() - 1);
}
try {
double v = Double.parseDouble(num);
value += Math.round(v * k);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid period - " + period + ", at '" + one + "', " + e.getMessage());
}
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment