gpt4 book ai didi

java - 两个本地时间的平均值

转载 作者:行者123 更新时间:2023-11-30 06:03:55 26 4
gpt4 key购买 nike

如何获取两个 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);

现在假设我有以下代码:

   //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;
}
}

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

  1. 我不能划分 LocalTime(只有在分别处理小时和分钟时才有效,但老实说,这有点太中世纪了
  2. 如果我不直接划分小时和分钟,它将高于 24:00,我不知道那时会发生什么:我想它会更进一步到 00:00 等而不是 36:00例子。

有没有人可以完成这段代码/解释哪里出了问题?

最佳答案

由于 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));
}

关于java - 两个本地时间的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50965815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com