0

I am using SingleLine chart from PhilJay/MPAndroidChart android library and i need a list of passed months of current year. So for example from Jan to Oct, but when is October pass then from Jan to Nov and so on. I tried these: Getting List of Month for Past 1 year in Android dynamically, and Calculate previous 12 months from given month - SimpleDateFormat but all of these are for previosly 12 months and i want from start of current year

@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);
    }
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
gojic
  • 363
  • 7
  • 20

1 Answers1

4

tl;dr ⇒ java.time

Months until (including) the current one as 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;
}

Months until (including) the current one as 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;
}

as an alternative, you can use the display name of the Month instead of using a 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;
}

The output of the second and third example:

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

when invoked like

System.out.println(String.join(", ", getMonthNamesOfCurrentYear()));
deHaar
  • 17,687
  • 10
  • 38
  • 51