LocalDateTime 两个字符串时间的均值
时间: 2023-11-09 12:00:44 浏览: 77
可以先将两个字符串时间转换为 LocalDateTime 对象,然后计算它们的时间戳的平均值,最后再将平均值转换为 LocalDateTime 对象即可。
示例代码:
```
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String time1 = "2022-01-01 12:00:00";
String time2 = "2022-01-02 12:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1 = LocalDateTime.parse(time1, formatter);
LocalDateTime dateTime2 = LocalDateTime.parse(time2, formatter);
long timestamp1 = dateTime1.toEpochSecond(ZoneOffset.of("+8"));
long timestamp2 = dateTime2.toEpochSecond(ZoneOffset.of("+8"));
long avgTimestamp = (timestamp1 + timestamp2) / 2;
LocalDateTime avgDateTime = LocalDateTime.ofEpochSecond(avgTimestamp, 0, ZoneOffset.of("+8"));
System.out.println(avgDateTime.format(formatter)); // 输出:2022-01-02 00:00:00
}
}
```
阅读全文