Search code examples
androidkotlincalendarandroid-viewpager

I want to get last three months from current month in Kotlin Using AndroidStudio, tab layout using viwepager2


guys actually my logic is that I want to basically show a current month with the last three months in tab layout which I am using to show the months wise data to the user so if present its "June" so I want to show tabs "April, May, June" these 3 months data to the user.


Solution

  • java.time

    Consider using java.time, the modern Java date and time API, for your date work. Sorry that I can write only Java.

        Month thisMonth = Month.from(YearMonth.now(ZoneId.systemDefault()));
        List<Month> months
                = Arrays.asList(thisMonth.minus(2), thisMonth.minus(1), thisMonth);
        for (Month m : months) {
            System.out.println(m.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH));
        }
    

    Output when running this month:

    April
    May
    June
    

    And don’t worry: this will work across New Year too. January minus 2 months will be November, for example.

    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 either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links