Anyone know of a Java library that can parse time strings such as “30min” or “2h 15min” or “2d 15h 30min” as milliseconds (or some kind of Duration object). Can Joda-Time do something like this?
(I have an ugly long method to maintain that does such parsing and would like to get rid of it / replace it with something that does a better job.)
You’ll probably have to tweak this a bit for your own format, but try something along these lines:
note that there is a
appendSuffixthat takes avariantsparameter if you need to make it more flexible.Update: Joda Time has since added
Period.toStandardDuration(), and from there you can usegetStandardSeconds()to get the elapsed time in seconds as along.If you’re using an older version without these methods you can still calculate a timestamp yourself by assuming the standard 24/hr in a day, 60min/hr, etc. (In this case, take advantage of the constants in the
DateTimeConstantsclass to avoid the need for magic numbers.)