I need to parse a duration string, of the form 98d 01h 23m 45s into milliseconds.
I was hoping there was an equivalent of SimpleDateFormat for durations like this, but I couldn’t find anything. Would anyone recommend for or against trying to use SDF for this purpose?
My current plan is to use regex to match against numbers and do something like
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher("98d 01h 23m 45s");
if (m.find()) {
int days = Integer.parseInt(m.group());
}
// etc. for hours, minutes, seconds
and then use TimeUnit to put it all together and convert to milliseconds.
I guess my question is, this seems like overkill, can it be done easier? Lots of questions about dates and timestamps turned up but this is a little different, maybe.
Using a
Patternis a reasonable way to go. But why not use a single one to get all four fields?Then use the indexed group fetch.
EDIT:
Building off of your idea, I ultimately wrote the following method