In this post, we will see how to get list of months name in Java.
Using DateFormatSymbols’s getMonth() method
We can use DateFormatSymbols's getMonth() to get list of months in Java. It will provide complete month names like January, February etc.
package org.arpit.java2blog;
import java.text.DateFormatSymbols;
import java.util.Arrays;
public class GetListOfMonths {
public static void main(String[] args) {
// Create DateFormatSymbols with default Locale
DateFormatSymbols dfs = new DateFormatSymbols();
String[] monthNames = dfs.getMonths();
System.out.println("Months are: "+ Arrays.toString(monthNames));
}
}
Output
Months are: [January, February, March, April, May, June, July, August, September, October, November, December, ]
Using DateFormatSymbols’s getShortMonths() method [ For short names]
If you need short names rather than complete months name, you can use DateFormatSymbols's getShortMonths().
package org.arpit.java2blog;
import java.text.DateFormatSymbols;
import java.util.Arrays;
public class GetListOfMonths {
public static void main(String[] args) {
// Create DateFormatSymbols with default Locale
DateFormatSymbols dfs = new DateFormatSymbols();
String[] shortMonthNames = dfs.getShortMonths();
System.out.println("Months with short names are: "+ Arrays.toString(shortMonthNames));
}
}
Output
Months with short names are: [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, ]
Using DateFormatSymbols’s getMonth() with Locale
If you are looking for month names in different Locale like German or French, you can specify Locale while creating object of DateFormatSymbols. It will work for both methods i.e. getMonth() and getShortMonths().
package org.arpit.java2blog;
import java.text.DateFormatSymbols;
import java.util.Arrays;
import java.util.Locale;
public class GetListOfMonths {
public static void main(String[] args) {
// Create DateFormatSymbols with default Locale
DateFormatSymbols dfs = new DateFormatSymbols(Locale.GERMAN);
String[] monthNames = dfs.getMonths();
System.out.println("German Months are: "+ Arrays.toString(monthNames));
String[] shortMonthNames = dfs.getShortMonths();
System.out.println("German Months in short name are: "+ Arrays.toString(shortMonthNames));
}
}
Output
German Months are: [Januar, Februar, März, April, Mai, Juni, Juli, August, September, Oktober, November, Dezember, ] German Months in short name are: [Jan., Feb., März, Apr., Mai, Juni, Juli, Aug., Sep., Okt., Nov., Dez., ]
Further reading:
That’s all about how to get list of months in Java.