0

I am having some strange output when I am attempting to get an average from a long value and converting it to a String (in HH:mm:ss) format. I'm using the Joda time library, which mostly has been a life saver.

Here's what I have so far:

//this is in a static class
public static Duration calculateTime(Date start, Date end) { 
    Duration duration = new Duration(start.getTime(), end.getTime());
    return duration;
}

public static String convertMillisToTime(long milliseconds) {
    return String.format("%02d:%02d:%02d", 
            TimeUnit.MILLISECONDS.toHours(milliseconds),
            TimeUnit.MILLISECONDS.toMinutes(milliseconds) - 
            TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliseconds)),
            TimeUnit.MILLISECONDS.toSeconds(milliseconds) - 
            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
}


long averageRunTime = 0;
averageRunTime += calculateTime(drs.startTime, drs.endTime).getMillis();

Since this is done in an array list, to get the average, I am taking

averageRunTime = averageRunTime / (long)arrayList.size();

when I get to the point of

convertMillisToTime(averageRunTime);

It's returning a value that is higher than any times I have. IE( I have no job times that are over 11 hours) but this is returning me a String with 11:mm:ss. Not quite sure WHY?

I used the convertMillisToTime from: How to convert milliseconds to "hh:mm:ss" format?

Can anyone point me in the right direction?

Thank you in advance,

  • RR

Edit: I've modified the code that converts the long to time using TimeUnit. It's strange though, I grabbed three runs (time streams) and got 09:14:17, 08:57:18, 09:10:25 for the length of each run, and the average is coming out as: 10:27:26.

Community
  • 1
  • 1
ResourceReaper
  • 555
  • 2
  • 10
  • 27
  • For each part of the time, you need to remove it from the amount of time you have, for example, once youve calculated the hours, you need to remove that amount of time from the time value you have. You should also be calculating from largest component to smallest (hours to seconds) – MadProgrammer Mar 19 '14 at 20:18
  • Which `Duration` class are you using? Forget it, just saw the jodatime tag – agbinfo Mar 19 '14 at 20:37

1 Answers1

0

You could just use a formatter from Joda Time instead, for example...

public static final PeriodFormatter PERIOD_FORMATTER = new PeriodFormatterBuilder().printZeroAlways().
                appendHours().appendSeparator(":").
                appendMinutes().appendSeparator(":").
                appendSeconds().appendSeparator(".").
                appendMillis().toFormatter();

public static String toString(Duration duration) {
    return duration == null ? "[invalid duration]" : duration.toPeriod().toString(PERIOD_FORMATTER);
}
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366