'short month names

I'm trying to get a short month name by passing the month int to a function. But it always returns 'Jan'

Here is the function:

public static String getMonthName_Abbr(int month) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, month);
    SimpleDateFormat month_date = new SimpleDateFormat("MMM");
    String month_name = month_date.format(month);
    return month_name; 
}


Solution 1:[1]

You simply need to pass cal.getTime() to your format call, rather than month itself.

See the working demo at http://ideone.com/kKrGY9

I am not sure why your code worked as given, seeing as how format expects a Date and not an int; however, if somehow it did, perhaps the value of month, being a small integer was interpreted as a time around the epoch (January 1, 1970). Just a thought, but at any rate, your function will work with that one small change.

Solution 2:[2]

public static String getMonthName_Abbr(int month) {
    final String[] allMonths = DateFormatSymbols.getInstance(Locale.getDefault()).getShortMonths();
    return (month >= 0 && month < allMonths.length) ? allMonths[months] : "Invalid month";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ray Toal
Solution 2 zen_of_kermit