java.time through desugaring
I should like to contribute the modern answer, the modern way to obtain your result. I recommend that these days you use java.time, the modern Java date and time API, for your date work. The others have nicely explained why your code gave an unexpected output, I am not repeating that.
int noOfMonths = 13;
YearMonth current = YearMonth.now(ZoneId.of("Africa/Tunis"));
for (int i = 0; i < noOfMonths; i++) {
System.out.println(current);
current = current.plusMonths(1);
}
When I ran this snippet today, the output was:
2019-01
2019-02
2019-03
2019-04
2019-05
2019-06
2019-07
2019-08
2019-09
2019-10
2019-11
2019-12
2020-01
If you want the month names, use a formatter:
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM u", Locale.ENGLISH);
int noOfMonths = 13;
YearMonth current = YearMonth.now(ZoneId.of("Africa/Tunis"));
for (int i = 0; i < noOfMonths; i++) {
System.out.println(current.format(monthFormatter));
current = current.plusMonths(1);
}
Output:
January 2019
February 2019
March 2019
April 2019
May 2019
June 2019
July 2019
August 2019
September 2019
October 2019
November 2019
December 2019
January 2020
When this question was asked nearly 7 years ago, Calendar
was the class we had for a task like this, also when it was poorly designed and cumbersome to work with. Not any longer: java.time came out with Java 8 just a couple of years later and has also been backported to Java 6 and 7.
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