First of all, I'd recommend to stop using Calendar
(as already suggested by this answer).
The old classes (Date
, Calendar
and SimpleDateFormat
) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.
For me it's not clear if you want a list with the month names or a map with the months in order (having the month name as key and the number as value). Anyway, here's a code for both (assuming that the default locale is English):
// created the sorted list
List<String> months = new ArrayList<>();
for (Month m : Month.values()) {
months.add(m.getDisplayName(TextStyle.FULL, Locale.getDefault()));
}
System.out.println("list: " + months);
// create the map (using LinkedHashMap, as it preserves the insertion order)
Map<String, Integer> map = new LinkedHashMap<>();
int i = 0;
for (String m : months) {
map.put(m, i++);
}
System.out.println("map: " + map);
The output will be:
list: [January, February, March, April, May, June, July, August, September, October, November, December]
map: {January=0, February=1, March=2, April=3, May=4, June=5, July=6, August=7, September=8, October=9, November=10, December=11}