【问题标题】:How to get list of passed months of this year java?java - 如何获取今年java已通过月份的列表?
【发布时间】:2020-10-06 12:51:03
【问题描述】:

我正在使用来自 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);
    }
}

【问题讨论】:

  • 获取当前日期的月份,然后从0循环到当前日期的月份-1?
  • Calendar.MONTH 从 0.. 0 = JANUARY 开始
  • 你为什么不用java.time.YearMonth?看起来这几乎就是你所需要的......说真的,不要为此使用Calendar 或任何其他过时的类......

标签: java android date-formatting


【解决方案1】:

tl;博士⇒java.time

距当前日期(包括)List&lt;YearMonth&gt;:

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&lt;String&gt;:

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()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多