1

I am facing issue with android calendar, I want to get previous to previous month, when i am trying it with current year this will achieve my goal, but when i am trying with previous year it fails. in my case today is 29/apr/2020 and i want feb/2019 return from calendar. please help me with this.

my code is following

Date dt = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int month = cal.get(Calendar.MONTH) - 2; // beware of month indexing from zero
            int year = cal.get(Calendar.YEAR)-1;
            int day = cal.get(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.MONTH, month);
            String formatMonth = new SimpleDateFormat("MMM").format(cal.getTime());
            String formatYear = new SimpleDateFormat("yy").format(cal.getTime());```  
Narendra
  • 101
  • 1
  • 4

1 Answers1

1

java.time and ThreeTenABP

Allow me to suggest that you use java.time, the modern Java date and time API, for your date work.

    YearMonth currentMonth = YearMonth.of(2020, Month.APRIL);
    YearMonth backThen = currentMonth.minusYears(1).minusMonths(2);

    String formatMonth = backThen.format(DateTimeFormatter.ofPattern("MMM"));
    String formatYear = backThen.format(DateTimeFormatter.ofPattern("yy"));

    System.out.printf("Month %s; year %s%n", formatMonth, formatYear);

Output on my computer is (locale dependent):

Month feb.; year 19

For the sake of a reproducible example I hardcoded the year and month. To start from the current month in some time zone use something like this:

    YearMonth currentMonth = YearMonth.now(ZoneId.of("Europe/Minsk"));

What went wrong in your code?

It’s the poor and confusing design of the Calendar and GregorianCalendar classes.

You said you ran your code on 29/apr/2020. This causes your Calendar to be set back to 29th February 2019. This date does not exist; there were only 28 days in February last year. Instead Calendar picks the day after February 28, that is, March 1. Causing you to get an incorrect month.

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161