Search code examples
javadatelocaltime

Average of two LocalTimes


How do I get the average of two LocalTimes? Can't find any suitable methods for this.

So for example 08:00 and 14:30, should return (14-8)/2 = 3 + minutes (30-00= 30)/2, so 3:15 And then smth like

Localtime xxx = LocalTime.parse("08:00", formatter).plus(3, ChronoUnit.HOURS); 
//and after that's done
xxx = xxx.plus(15, ChronoUnit.MINUTES);

Now suppose that I have the following code:

   //this means that if code is 08:00, it should look whether the average of Strings split21 and split2 (which are put in time2 and time3, where time2 is ALWAYS before time3) is before 08:00
   if(code1.contains("800")) {

        LocalTime time1 = LocalTime.parse("08:00", formatter);
        LocalTime time2 = LocalTime.parse(split21, formatter);
        LocalTime time3 = LocalTime.parse(split2, formatter);
        LocalTime average = 
        if(time2.isBefore(time1)) {
            return true;
        }
        else {
            return false;
        }
    }

Obviously I can use.getHour and .getMinute , but there are two problems here.

  1. I cannot divide LocalTime (only if working with hours and minutes seperately but honestly that's a bit too medieval
  2. If I don't directly divide the hours and minutes, it will be higher than 24:00 and I've no clue what will happen then: I suppose it goes further with 00:00 etc instead of 36:00 for example.

Is there someone who could finish this code/explain what's wrong?


Solution

  • Since a LocalTime is effectively defined by the nano seconds since midnight, you can do something like this:

    public static LocalTime average(LocalTime t1, LocalTime... others) {
      long nanosSum = t1.toNanoOfDay();
      for (LocalTime other : others) {
        nanoSum += others.toNanoOfDay();
      }
      return LocalTime.ofNanoOfDay(nanoSum / (1+others.length));
    }