2

I wanna programmatically convert an integer in the range 1-12 to corresponding month name. (e.g. 1 -> January, 2 -> February) etc using Java Calendar class in one statement.

Note : I want to do it using Java Calendar class only. Don't suggest any switch-case or string array solution.

Thanks.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Red Hyena
  • 2,988
  • 5
  • 25
  • 24

4 Answers4

8

The Calendar class is not the best class to use when it comes obtaining the localized month name in one statement.

The following is an example of obtaining the month name of a desired month specified by a int value (where January is 1), using only the Calendar class:

// Month as a number.
int month = 1;

// Sets the Calendar instance to the desired month.
// The "-1" takes into account that Calendar counts months
// beginning from 0.
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, month - 1);

// This is to avoid the problem of having a day that is greater than the maximum of the
// month you set. c.getInstance() copies the whole current dateTime from system 
// including day, if you execute this on the 30th of any month and set the Month to 1 
// (February) getDisplayName will get you March as it automatically jumps to the next              
// Month
c.set(Calendar.DAY_OF_MONTH, 1);    

// Returns a String of the month name in the current locale.
c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());

The above code will return the month name in the system locale.

If another locale is required, one can specify another Locale by replacing the Locale.getDefault() with a specific locale such as Locale.US.

Adham
  • 490
  • 4
  • 12
coobird
  • 159,216
  • 35
  • 211
  • 226
  • Though not in one statement, this is a good enough answer for me! Thanks! – Red Hyena Dec 31 '09 at 06:08
  • I was actually looking at the getDisplayNames() method. Any idea why it returns a Map? I would think Map would be more logical since you could access any month with the appropriate Integer value. I can't seen any requirement to access the Map with a month name to get its integer value. I guess thats what you mean when you say its not the best class to use to get the month. – camickr Dec 31 '09 at 06:21
  • @camickr: The `getDisplayNames` method seems like it has been retrofitted to the `Calendar` class to support some new use-case that arose from an addition of another class. I would suspect `DateFormatSymbols` as it seems like many parts of that class and the aforementioned method has been added in JDK 1.6. – coobird Dec 31 '09 at 06:41
  • @coobird, I didn't look at the method close enough and I see that when using Styles.ALL_STYLES the method returns both short and long descriptions so to keep the key unique, you need the use the month as a String, not an Integer. – camickr Dec 31 '09 at 06:54
3

Use DateFormatSymbols

Proudly copied and pasted from bluebones.net:

import java.text.*;

String getMonthForInt(int m) {
    String month = "invalid";
    DateFormatSymbols dfs = new DateFormatSymbols();
    String[] months = dfs.getMonths();
    if (m >= 0 && m <= 11 ) {
        month = months[m];
    }
    return month;
}
Anurag
  • 140,337
  • 36
  • 221
  • 257
2

Did you read the API? The method getDisplayName(...) looks like a good place to start. Doing it in one statement is a terrible requirement.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

tl;dr

Month.of( 12 ).getDisplayName( TextStyle.FULL , Locale.US )

…or…

Month.DECEMBER.getDisplayName( TextStyle.FULL , Locale.US )

December

Using java.time

The modern way to get the localized name of a month is with the java.time.Month enum. This class is part of the java.time package than now supplants the troublesome old legacy date-time classes such as Date and Calendar.

To localize, specify:

  • TextStyle to determine how long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Example code.

Month month = Month.of( 7 );
String outputConstantName = month.toString();
String outputMonthNameEnglish = month.getDisplayName( TextStyle.FULL , Locale.US );
String outputMonthQuébec = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

month.toString(): JULY

outputMonthNameEnglish: July

outputMonthQuébec: juillet

Using the Month enum objects by name rather than month number can be handy, easier to read, and less error-prone.

String output = Month.JULY.getDisplayName( TextStyle.FULL , Locale.US ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154