user971741
user971741

Reputation:

Calendar.getDisplayName returning null

I am trying to get display name of a month through this:

    final Calendar c = Calendar.getInstance();
    String monthName=c.getDisplayName(monthOfYear, Calendar.SHORT, Locale.US);//monthOfYear: 6

but the function is always returning null

please help me.

Upvotes: 1

Views: 796

Answers (2)

TWiStErRob
TWiStErRob

Reputation: 46480

You might want to consider ditching Calendar, it's a little heavy weight for such a simple task:

int monthOfYear = Calendar.JULY; // 6
String monthName = new DateFormatSymbols(Locale.US).getShortMonths()[monthOfYear];

Note that you can cache (even in a static variable) return value of getShortMonths() and index for different months later, just be careful, numbering starts from 0 (=JANUARY). It's worth caching since getShortMonths() returns a new mint array every time.

Please consider using DateFormatSymbols.getInstance(Locale.US) instead of new if you're targeting > API Level 9.

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1006664

Else how can i get the display name of one particular month.

Step #1: Create a Calendar for a date that is in that particular month.

Step #2: Call getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US) on the Calendar object from Step #1.

Step #3: Beer.

Note: step #3 is optional.

Upvotes: 1

Related Questions