localdatetime Duration计算平均
时间: 2024-04-30 08:22:27 浏览: 70
以下是使用Java 8中的LocalDateTime和Duration计算平均时间的示例代码:
```java
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<LocalDateTime> timestamps = List.of(
LocalDateTime.of(2021, 10, 1, 10, 30),
LocalDateTime.of(2021, 10, 2, 11, 45),
LocalDateTime.of(2021, 10, 3, 12, 0),
LocalDateTime.of(2021, 10, 4, 9, 15),
LocalDateTime.of(2021, 10, 5, 14, 30)
);
LocalDateTime sum = timestamps.stream()
.reduce(LocalDateTime.MIN, LocalDateTime::plus);
LocalDateTime average = sum.dividedBy(timestamps.size());
System.out.println("Average timestamp: " + average);
Duration totalDuration = Duration.ZERO;
for (int i = 0; i < timestamps.size() - 1; i++) {
Duration duration = Duration.between(timestamps.get(i), timestamps.get(i + 1));
totalDuration = totalDuration.plus(duration);
}
Duration averageDuration = totalDuration.dividedBy(timestamps.size() - 1);
System.out.println("Average duration between timestamps: " + averageDuration);
}
}
```
该示例首先创建了一个本地日期时间列表,然后使用流将它们全部加起来,然后计算平均值。接下来,它计算了时间戳之间的平均持续时间。该过程循环遍历时间戳列表,并计算相邻时间戳之间的持续时间,并将它们全部加起来。最后,计算平均持续时间并输出结果。
阅读全文