java 获取截至当前的年月的List
时间: 2023-09-02 19:09:45 浏览: 44
好的,针对您的问题,我可以给您提供以下Java代码实现:
```java
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
public class YearMonthList {
public static List<YearMonth> getYearMonthList() {
List<YearMonth> yearMonthList = new ArrayList<>();
YearMonth currentYearMonth = YearMonth.now();
int currentYear = currentYearMonth.getYear();
int currentMonth = currentYearMonth.getMonthValue();
for (int i = 2000; i <= currentYear; i++) {
int startMonth = (i == 2000) ? 1 : currentMonth;
for (int j = startMonth; j <= 12; j++) {
YearMonth yearMonth = YearMonth.of(i, j);
yearMonthList.add(yearMonth);
}
}
return yearMonthList;
}
public static void main(String[] args) {
List<YearMonth> yearMonthList = getYearMonthList();
for (YearMonth yearMonth : yearMonthList) {
System.out.println(yearMonth);
}
}
}
```
这段代码实现了获取截至当前的年月的List。具体实现过程如下:
1. 首先定义一个`getYearMonthList`方法,该方法返回一个`List<YearMonth>`类型的列表;
2. 获取当前年月;
3. 循环遍历从2000年到当前年份的每一年,计算每一年的起始月份和结束月份,并将每一年的所有月份添加到`yearMonthList`中;
4. 最后返回`yearMonthList`列表。
在`main`方法中,我们可以测试`getYearMonthList`方法,输出结果为从2000年1月到当前年月的所有年月。