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.
Is there someone who could finish this code/explain what's wrong?
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));
}