tags:

views:

2088

answers:

4

I get an integer and I need to convert to a month names in various locales:

Example for locale en-us:
1 -> January
2 -> February

Example for locale es-mx:
1 -> Enero
2 -> Febrero

+6  A: 
import java.text.DateFormatSymbols;
public String getMonth(int month) {
    return new DateFormatSymbols().getMonths()[month-1];
}
joe
Do you not need 'month-1', since the array is zero based ? atomsfat wants 1 -> January etc.
Brian Agnew
He does need month-1, because the month is the 1-based month number which needs to be converted to the zero-based array position
Sam Barnum
This works too, you need to construct DateFormatSymbols with the locale though.
stevedbrown
public String getMonth(int month, Locale locale) { return DateFormatSymbols.getInstance(locale).getMonths()[month-1];}
atomsfat
A: 

How about SimpleDateFormat?

Sinan Ünür
+2  A: 

I would use SimpleDateFormat. Someone correct me if there is an easier way to make a monthed calendar though, I do this in code now and I'm not so sure.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;


public String formatMonth(int month, Locale locale) {
    DateFormat formatter = new SimpleDateFormat("MMMMM", locale);
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.MONTH, month-1);
    return formatter.format(calendar.getTime());
}
stevedbrown
+1  A: 

Here's how I would do it. I'll leave range checking on the int month up to you.

import java.text.DateFormatSymbols;

public String formatMonth(int month, Locale locale) {
    DateFormatSymbols symbols = new DateFormatSymbols(locale);
    String[] monthNames = symbols.getMonths();
    return monthNames[month - 1];
}
Bill the Lizard