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,但是这里有两个问题。
是否有人可以完成此代码/解释出什么问题?
由于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)