Is there a java library that converts strings describing measures of time (e.g. "1d 1m 1s") to milliseconds?
java, spring, string
Solution
The parser is not too complex:
public static long parse(String input) {
long result = 0;
String number = "";
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
number += c;
} else if (Character.isLetter(c) && !number.isEmpty()) {
result += convert(Integer.parseInt(number), c);
number = "";
}
}
return result;
}
private static long convert(int value, char unit) {
switch(unit) {
case 'd' : return value * 1000*60*60*24;
case 'h' : return value * 1000*60*60;
case 'm' : return value * 1000*60;
case 's' : return value * 1000;
}
return 0;
}
The code is pretty fault tolerant, it just ignores almost anything it can't decode (and it ignores any whitspace, so it accepts "1d 1s", "1s 1d", "1d20m300s" and so on).
Problem
When setting issue estimates in JIRA, you can enter a string like `"1d 2h 30m"` and JIRA will translate this (I'm assuming) into a corresponding number of milliseconds. Is there an available Java library that does this? I'm using a Spring managed bean that takes a property indicating how often a directory ought to be purged, and I'd like to allow the configuration to take a human-readable string rather than an explicit number of milliseconds. Alternatively, if there's a better approach I'm not thinking of, I'd love to hear it.