Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing duration string into milliseconds

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.

like image 512
skynet Avatar asked Jun 13 '12 19:06

skynet


People also ask

How do you pass duration in Java?

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() .

How do you represent milliSeconds in Java?

millis(); System. out. println(milliSeconds); Output:: 1534749202051 Explanation:: when millis() is called, then it returns a current instant of Class Object in milliseconds.

How does duration of work in Java?

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.

Is Java duration immutable?

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.


1 Answers

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.

like image 58
npe Avatar answered Oct 14 '22 13:10

npe