android - 在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中实现这件事。谢谢。
解决方案
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
子包中导入日期和时间类。
链接
- Oracle 教程:日期时间解释如何使用 java.time。
- Java 规范请求 (JSR) 310,
java.time
第一次描述的地方。 - ThreeTen Backport 项目,
java.time
Java 6 和 7 的反向移植(ThreeTen for JSR-310)。 - ThreeTenABP , ThreeTen Backport 的 Android 版
- 问题:如何在Android项目中使用ThreeTenABP,有非常详尽的解释。
推荐阅读
- javascript - 使用 Tab 键导航时触发 Click 事件
- python-3.x - Pandas:在记录级别获取排序值的列名
- aws-cdk - AWS cdk Stack 部署顺序
- ruby-on-rails - 无法将数据设置到rails中的数据库中
- reactjs - 如何从 Flask api 服务器获取图像响应,然后将其显示在反应应用程序中
- html - 导航栏未在 Chrome 开发工具中显示为正文的子元素
- c - 初始化的结构成员不能用作 C 中的整数常量吗?
- reactjs - 如何自动从上到下滚动以响应信使?
- python - django social auth 额外参数和白名单域不起作用
- hl7-fhir - FHIR:是否存在私人实体采用问题?