如何获得今年Java过去月份的列表?

问题描述

我正在使用PhilJay / MPAndroidChart android库中的SingleLine图表,并且需要本年度过去月份的列表。例如,从一月到十月,但是什么时候是十月,那么从一月到十一月,依此类推。 我尝试了这些:Getting List of Month for Past 1 year in Android dynamically, 和Calculate previous 12 months from given month - SimpleDateFormat 但是所有这些大概都用了12个月,我想从今年开始算起

@SuppressLint("SimpleDateFormat")
private void handleXAxis() {
    List<String> allDates = new ArrayList<>();
    String maxDate = "Jan";
    SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
    Calendar cal = Calendar.getInstance();
    try {
        cal.setTime(Objects.requireNonNull(monthDate.parse(maxDate)));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    for (int i = 1; i <= 12; i++) {
        String month_name1 = monthDate.format(cal.getTime());
        allDates.add(month_name1);
        cal.add(Calendar.MONTH,-1);
    }
}

解决方法

tl; dr⇒java.time

直到(包括)当前月份为List<YearMonth>的月份:

public static List<YearMonth> getMonthsOfCurrentYear() {
    YearMonth currentMonth = YearMonth.now();
    List<YearMonth> yearMonths = new ArrayList<>();
    
    for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
        yearMonths.add(YearMonth.of(currentMonth.getYear(),month));
    }
    
    return yearMonths;
}

直到(包括)当前月份为List<String>的月份:

public static List<String> getMonthNamesOfCurrentYear() {
    YearMonth currentMonth = YearMonth.now();
    List<String> yearMonths = new ArrayList<>();
    
    for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
        yearMonths.add(YearMonth.of(currentMonth.getYear(),month)
                                .format(DateTimeFormatter.ofPattern("MMM",Locale.ENGLISH)));
    }
    
    return yearMonths;
}

或者,您可以使用Month的显示名称,而不要使用DateTimeFormatter.ofPattern("MMM")

public static List<String> getMonthNamesOfCurrentYear() {
    YearMonth currentMonth = YearMonth.now();
    List<String> yearMonths = new ArrayList<>();
    
    for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
        yearMonths.add(Month.of(month)
                            .getDisplayName(TextStyle.SHORT,Locale.ENGLISH));
    }
    
    return yearMonths;
}

第二个和第三个示例的输出:

Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct

像调用时一样

System.out.println(String.join(",",getMonthNamesOfCurrentYear()));

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...