Java 根据传入的年份字符串,得到当年的月份List,例如:2022-01
时间: 2024-02-18 18:02:22 浏览: 18
可以使用Java中的DateTimeFormatter和LocalDate类来实现这个功能。以下是一个示例代码,它将传入的年份字符串解析为LocalDate对象,并使用循环获取每个月份的名称并将其添加到List中。
```java
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class GetMonthList {
public static void main(String[] args) {
String yearMonthString = "2022-01";
List<String> monthList = getMonthList(yearMonthString);
System.out.println(monthList);
}
public static List<String> getMonthList(String yearMonthString) {
List<String> monthList = new ArrayList<>();
// 将年份字符串解析为LocalDate对象
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM", Locale.getDefault());
LocalDate yearMonth = LocalDate.parse(yearMonthString + "-01", formatter);
// 循环获取每个月份的名称
for (Month month : Month.values()) {
LocalDate date = LocalDate.of(yearMonth.getYear(), month, 1);
if (date.isBefore(yearMonth) || date.equals(yearMonth)) {
String monthName = month.getDisplayName(java.time.format.TextStyle.FULL, Locale.getDefault());
monthList.add(monthName);
}
}
return monthList;
}
}
```
在上面的示例中,我们首先使用DateTimeFormatter将传入的年份字符串解析为LocalDate对象。接下来,我们循环获取每个月份的名称,并将其添加到List中。在每次循环时,我们使用LocalDate.of方法创建一个表示该月份的LocalDate对象,并使用isBefore和equals方法来检查该月份是否在传入的年份之前或等于传入的年份。最后,我们返回该List。