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