1

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; 
}
DaveSav
  • 1,334
  • 4
  • 21
  • 40
  • Something is strange here. According to the [docs for SimpleDateFormat](http://developer.android.com/reference/java/text/SimpleDateFormat.html), the format method requires a `Date` and you passed it an `int`. – Ray Toal Dec 23 '12 at 01:10
  • I don't know. I was expecting some magic to happen. That code block is just my latest attempt at trying to implement the answer given at http://stackoverflow.com/questions/6192781/how-to-get-month-as-a-string-in-android – DaveSav Dec 23 '12 at 01:14
  • Oh I see, pass `cal.getTime()` to the `format` method. – Ray Toal Dec 23 '12 at 01:16
  • Thank you, Ray. That has worked. My app is for api 8 and above, but I only have a real api 8 device to work with; would your solution work with higher api's ? – DaveSav Dec 23 '12 at 01:24
  • Yes, this will work with API 8, as `Calendar` and `SimpleDateFormat` are plain Java and have been there since the beginning. The differences between 7 and 8 are [here](http://developer.android.com/sdk/api_diff/8/changes.html) -- there are no changes in any of the classes used in your example. – Ray Toal Dec 23 '12 at 01:49

2 Answers2

2

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.

Ray Toal
  • 82,964
  • 16
  • 166
  • 221
  • Yeah, the first 31 * 24 * 60 * 60 * 1000 milliseconds would be timestamps that are in the month of January, and he was passing values from 0 to 11. So straight into the first second of Jan 1, 1970. Funny bug, really :D – Davor Jul 14 '13 at 16:04
0
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";
}
zen_of_kermit
  • 1,286
  • 2
  • 12
  • 18