首页 > 解决方案 > 在Android中动态获取过去1年的月份列表

问题描述

当天的问候。

在我的应用程序中,我目前静态显示了月份列表。

但是,我想要动态的月份列表。即小于或等于当年当前运行月份的 12 个月。

例如今天是 2020 年 5 月 2 日,因此,列表应如下所示:

2019 年 6 月 2019 年 7 月 2019 年 8 月 2019 年 9 月 2019 年 10 月 2019 年 11 月 2019 年 12 月 2020 年 1 月 2020 年 2 月 2020 年 3 月 2020 年 4 月 2020 年 5 月

请指导我如何在Android中实现这件事。谢谢。

标签: androidmonthcalendar

解决方案


java.time 和 ThreeTenABP

final int monthsInYear = 12;
YearMonth currentMonth = YearMonth.now(ZoneId.of("Pacific/Kosrae"));
YearMonth sameMonthLastYear = currentMonth.minusYears(1);
List<YearMonth> months = new ArrayList<>(monthsInYear);
for (int i = 1; i <= monthsInYear; i++) {
    months.add(sameMonthLastYear.plusMonths(i));
}

System.out.println(months);

输出:

[2019-06、2019-07、2019-08、2019-09、2019-10、2019-11、2019-12、2020-01、2020-02、2020-03、2020-04、2020-05]

我建议您将YearMonth对象保留在列表中。对于格式化输出,请使用DateTimeFormatter

    DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM, uuuu", Locale.ENGLISH);
    for (YearMonth ym : months) {
        System.out.println(ym.format(monthFormatter));
    }
Jun, 2019
Jul, 2019
Aug, 2019
... (cut) ...
Apr, 2020
May, 2020

问题:java.time 不需要 Android API 级别 26 吗?

java.time 在较旧和较新的 Android 设备上都能很好地工作。它只需要至少Java 6

  • 在 Java 8 及更高版本以及更新的 Android 设备(从 API 级别 26 开始)中,现代 API 是内置的。
  • 在非 Android Java 6 和 7 中获得 ThreeTen Backport,现代类的后向端口(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从org.threeten.bp子包中导入日期和时间类。

链接


推荐阅读