一个list里面包含的时间,用java 怎么获取同一天的时间
时间: 2024-02-01 20:04:40 浏览: 27
可以通过Java 8的LocalDate类来实现。首先需要将时间转换为LocalDateTime对象,然后使用toLocalDate()方法获取LocalDate对象,最后比较两个LocalDate对象是否相等即可判断是否为同一天。
示例代码:
```java
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> times = new ArrayList<>();
times.add("2021-09-15 10:00:00");
times.add("2021-09-15 14:30:00");
times.add("2021-09-16 08:00:00");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDate targetDate = LocalDate.of(2021, 9, 15);
for (String timeStr : times) {
LocalDateTime time = LocalDateTime.parse(timeStr, formatter);
LocalDate date = time.toLocalDate();
if (date.equals(targetDate)) {
System.out.println(timeStr + " is on the target date.");
}
}
}
}
```
输出结果:
```
2021-09-15 10:00:00 is on the target date.
2021-09-15 14:30:00 is on the target date.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)