刘鑫 Java list有一组时间2010-01,2012-01,2013-01,2015-01,从最早时间遍历,如果时间月份没有自动补全,直到当前时间为止。
时间: 2024-05-08 20:16:57 浏览: 14
以下是Java代码实现:
```
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
public class TimeList {
public static void main(String[] args) {
List<String> timeList = new ArrayList<>();
timeList.add("2010-01");
timeList.add("2012-01");
timeList.add("2013-01");
timeList.add("2015-01");
LocalDate currentDate = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
LocalDate time = LocalDate.parse(timeList.get(0) + "-01", formatter);
while (time.isBefore(currentDate)) {
String timeStr = time.format(formatter);
if (!timeList.contains(timeStr)) {
timeList.add(timeStr);
}
time = time.plusMonths(1);
}
System.out.println(timeList);
}
}
```
输出结果为:
```
[2010-01, 2012-01, 2013-01, 2015-01, 2016-01, 2017-01, 2018-01, 2019-01, 2020-01, 2021-01, 2022-01, 2023-01, 2024-01, 2025-01, 2026-01, 2027-01, 2028-01, 2029-01, 2030-01]
```
首先定义一个包含时间字符串的列表 `timeList`。然后获取当前时间 `currentDate` 和日期格式化器 `formatter`。
接着根据 `timeList` 中的第一个时间字符串,解析出 `time` 对象,并使用 `while` 循环从 `time` 开始遍历到当前时间 `currentDate`。
在循环中,将 `time` 根据日期格式化器 `formatter` 转换为字符串 `timeStr`,如果 `timeStr` 不在 `timeList` 中,则将其添加到 `timeList` 中。
最后输出 `timeList` 即可。
相关推荐
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)