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.
The length of the duration is stored using two fields - seconds and nanoseconds. The nanoseconds part is a value from 0 to 999,999,999 that is an adjustment to the length in seconds. The total duration is defined by calling this method and getSeconds() .
millis(); System. out. println(milliSeconds); Output:: 1534749202051 Explanation:: when millis() is called, then it returns a current instant of Class Object in milliseconds.
Duration of() method in Java This method requires two parameters i.e. the time value and the temporal unit for that value. It returns the time duration with the particular value and temporal unit.
Duration is the value-based Class present in the Java time library. It's used to get time-based amount of time. This class is immutable and thread-safe.
Check out PeriodFormatter
and PeriodParser
from JodaTime library.
You can also use PeriodFormatterBuilder
to build a parser for your strings like this
String periodString = "98d 01h 23m 45s";
PeriodParser parser = new PeriodFormatterBuilder()
.appendDays().appendSuffix("d ")
.appendHours().appendSuffix("h ")
.appendMinutes().appendSuffix("m ")
.appendSeconds().appendSuffix("s ")
.toParser();
MutablePeriod period = new MutablePeriod();
parser.parseInto(period, periodString, 0, Locale.getDefault());
long millis = period.toDurationFrom(new DateTime(0)).getMillis();
Now, all this (especially the toDurationFrom(...)
part) may look tricky, but I really advice you to look into JodaTime
if you're dealing with periods and durations in Java.
Also look at this answer about obtaining milliseconds from JodaTime period for additional clarification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With