java 获取一组时间中最后的时间
时间: 2024-01-28 13:03:04 浏览: 23
可以使用Java中的DateTimeFormatter和LocalDateTime类来实现这个功能。你可以将时间字符串转换为LocalDateTime对象,然后比较它们的大小,找到最晚的时间。
以下是一个示例代码,假设有一个时间字符串数组strArray:
```
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime latestTime = LocalDateTime.MIN;
for (String str : strArray) {
LocalDateTime time = LocalDateTime.parse(str, formatter);
if (time.isAfter(latestTime)) {
latestTime = time;
}
}
System.out.println("最后的时间是:" + latestTime.format(formatter));
}
}
```
在这个示例代码中,我们使用了DateTimeFormatter来指定时间字符串的格式,并使用LocalDateTime.parse()方法将时间字符串转换为LocalDateTime对象。然后,我们将每个时间对象与最后的时间对象比较,以找到最晚的时间。最后,我们使用DateTimeFormatter.format()方法将最后的时间对象转换回时间字符串并输出。
请注意,这个示例代码假设所有的时间字符串都是合法的,并且时间字符串的格式都是一样的。如果你的实际情况不是这样的,你需要对代码进行适当的修改,以确保它能正确地处理所有的情况。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)