How can I get Month Name from Calendar?

Is there a oneliner to get the name of the month when we know:

int monthNumber  = calendar.get(Calendar.MONTH)

Or what is the easiest way?


Solution 1:

You can achieve it using SimpleDateFormat, which is meant to format date and times:

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));

Solution 2:

String getMonthForInt(int num) {
    String month = "wrong";
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] months = dfs.getMonths();
    if (num >= 0 && num <= 11) {
        month = months[num];
    }
    return month;
}

Solution 3:

As simple as this

mCalendar = Calendar.getInstance();    
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());

Solution 4:

This is the solution I came up with for a class project:

public static String theMonth(int month){
    String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
    return monthNames[month];
}

The number you pass in comes from a Calendar.MONTH call.

Solution 5:

If you have multi-language interface, you can use getDisplayName to display the name of month with control of displaying language.

Here is an example of displaying the month name in English, French, Arabic and Arabic in specific country like "Syria":

Calendar c = Calendar.getInstance();
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRANCE ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar") ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar", "SY") ) );
System.out.println(c.getTime().toString());

The result is:

January
janvier
يناير
كانون الثاني
Sat Jan 17 19:31:30 EET 2015