【问题标题】:Getting List of Month for Past 1 year in Android dynamically在Android中动态获取过去1年的月份列表
【发布时间】:2020-05-02 07:46:14
【问题描述】:

今天的问候。

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

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

例如今天是 2020 年 5 月 2 日,所以,列表应该如下:

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

请指导我如何在 Android 中实现此功能。 谢谢。

【问题讨论】:

    标签: android monthcalendar


    【解决方案1】:
    val formatter = SimpleDateFormat("MMM, yyyy")
    val list = arrayListOf<String>()
    Calendar.getInstance().let {
        calendar ->
        calendar.add(Calendar.MONTH, -11)
        for (i in 0 until 12) {
            list.add(formatter.format(calendar.timeInMillis))
            calendar.add(Calendar.MONTH, 1)
        }
    }
    print(list)
    

    【讨论】:

      【解决方案2】:

      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,这是现代类的后向端口(JSR 310 的 ThreeTen;请参阅底部的链接)。
      • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从 org.threeten.bp 导入日期和时间类以及子包。

      链接

      【讨论】:

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