Getting List of Month for Past 1 year in Android dynamically

你说的曾经没有我的故事 提交于 2021-02-11 13:59:11

问题


Greetings of the day.

In my application, I have displayed list of months statically currently.

But, I want list of months dynamically. i.e. 12 months which are lesser or equal to current running month of current year.

For Example today is 2nd May 2020, So, List should be as below :

Jun, 2019. Jul, 2019. Aug, 2019. Sep, 2019. Oct, 2019. Nov, 2019. Dec, 2019. Jan, 2020. Feb, 2020. Mar, 2020. Apr, 2020. May, 2020.

Please guide how can I achieve this thing in Android. Thanks.


回答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 and 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);

Output:

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

I recommend you keep YearMonth objects in your list. For formatted output use a 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

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.


来源:https://stackoverflow.com/questions/61556013/getting-list-of-month-for-past-1-year-in-android-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!