簡體   English   中英

如何獲取今年java過去的月份列表?

[英]How to get list of passed months of this year java?

我正在使用 PhilJay/MPAndroidChart android 庫中的 SingleLine 圖表,我需要一份當年過去月份的列表。 所以例如從一月到十月,但是十月什么時候過去,然后從一月到十一月等等。 我嘗試了這些: 在 Android 中動態獲取過去 1 年的月份列表,並計算給定月份的前 12 個月 - 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;博士 ⇒ 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()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM