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
Pattern
is 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
Check out
PeriodFormatter
andPeriodParser
from JodaTime library.You can also use
PeriodFormatterBuilder
to build a parser for your strings like thisNow, all this (especially the
toDurationFrom(...)
part) may look tricky, but I really advice you to look intoJodaTime
if you're dealing with periods and durations in Java.Also look at this answer about obtaining milliseconds from JodaTime period for additional clarification.
The new java.time.Duration class in Java 8 let's you parse durations out of the box:
the format is slightly different so would need adjusting prior to parsing.