两个本地时间的平均值

Not*_*tch 2 java date localtime

如何获得两个的平均值LocalTimes?找不到适合的方法。

因此,例如08:00和14:30,应该返回(14-8)/ 2 = 3 +分钟(30-00 = 30)/ 2,所以3:15然后像

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

现在假设我有以下代码:

   //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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

显然我可以使用.getHour和.getMinute,但是这里有两个问题。

  1. 我无法划分LocalTime(仅当单独处理小时和分钟时才适用,但说实话这有点太过时了
  2. 如果我不直接划分小时和分钟,它将高于24:00,但我不知道会发生什么:我想它会以00:00等而不是36:00继续。

是否有人可以完成此代码/解释出什么问题?

Joa*_*uer 5

由于a LocalTime是由午夜以来的纳秒有效定义的,因此您可以执行以下操作:

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));
}
Run Code Online (Sandbox Code Playgroud)