如何得到两个LocalTimes的平均值?找不到合适的方法。
因此,例如08:00和14:30,应该返回(14-8)/2 =3+ like (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;
}
}显然,我可以use.getHour和.getMinute,但是这里有两个问题。
有没有人能完成这段代码/解释出了什么问题?
发布于 2018-06-21 10:59:01
由于从午夜开始,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));
}发布于 2018-06-21 10:17:57
我想你的意思是这样的:
public static LocalTime average(LocalTime time1, LocalTime time2) {
if (time1.isAfter(time2)) {
return LocalTime.of(
time1.plusHours(time2.getHour()).getHour() / 2,
time1.plusMinutes(time2.getMinute()).getMinute() / 2
);
} else {
return LocalTime.of(
time2.plusHours(time1.getHour()).getHour() / 2,
time2.plusMinutes(time1.getMinute()).getMinute() / 2
);
}
}然后您可以调用您的方法倍数:
LocalTime time1 = LocalTime.of(14, 30);
LocalTime time2 = LocalTime.of(8, 00);
LocalTime result = average(time1, time2);如果有三次,例如:
LocalTime time1 = LocalTime.of(14, 30);
LocalTime time2 = LocalTime.of(8, 00);
LocalTime time3 = LocalTime.now();
LocalTime result = average(average(time1, time2), time3);..and等
第一个示例的输出
11:15发布于 2018-06-21 11:09:20
您可以使用Java8 java.time包轻松地使用LocalTime.ofSecondOfDay(long)方法来完成这一任务。这实际上是一天中每小时和每分钟(和第二分钟)的总和。
public static LocalTime average(LocalTime... times) {
return LocalTime.ofSecondOfDay((long) Arrays.stream(times)
.mapToInt(LocalTime::toSecondOfDay)
.average()
.getAsDouble());
}LocalTime t1 = LocalTime.of(8, 0);
LocalTime t2 = LocalTime.of(14, 30);
System.out.println(average(t1, t2)); // Prints 11:15https://stackoverflow.com/questions/50965815
复制相似问题