Java get month string from integer

JavaDate

Java Problem Overview


Is there a better way to compact this method i.e. reduce the cyclomatic complexity by avoid the switch cases?

String monthString;
        switch (month) {
            case 1:  monthString = "January";       break;
            case 2:  monthString = "February";      break;
            case 3:  monthString = "March";         break;
            case 4:  monthString = "April";         break;
            case 5:  monthString = "May";           break;
            case 6:  monthString = "June";          break;
            case 7:  monthString = "July";          break;
            case 8:  monthString = "August";        break;
            case 9:  monthString = "September";     break;
            case 10: monthString = "October";       break;
            case 11: monthString = "November";      break;
            case 12: monthString = "December";      break;
            default: monthString = "Invalid month"; break;
        }
        System.out.println(monthString);

Java Solutions


Solution 1 - Java

Try:

import java.text.DateFormatSymbols;
monthString = new DateFormatSymbols().getMonths()[month-1];

Alternatively, you could use SimpleDateFormat:

import java.text.SimpleDateFormat;
System.out.println(new SimpleDateFormat("MMMM").format(date));

(You'll have to put a date with your month in a Date object to use the second option).

Solution 2 - Java

Month enum

You could use the Month enum. This enum is defined as part of the new java.time framework built into Java 8 and later.

int monthNumber = 10;
Month.of(monthNumber).name();

The output would be:

>OCTOBER

Localize

Localize to a language beyond English by calling getDisplayName on the same Enum.

String output = Month.OCTOBER.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH );

output:

>octobre

Solution 3 - Java

Take an array containing months name.

String[] str = {"January",      
   "February",
   "March",        
   "April",        
   "May",          
   "June",         
   "July",         
   "August",       
   "September",    
   "October",      
   "November",     
   "December"};

Then where you wanna take month use like follow:

if(i<str.length)
    monthString = str[i-1];
else
    monthString = "Invalid month";

Solution 4 - Java

You could have an array of strigs and access by index.

  String months[] = {"January", "February", "March", "April",
                     "May", "June", "July", "August", "September",
                     "October", "November", "December"};

Solution 5 - Java

This has already been mentioned, but here is a way to place the code within a method:

	public static String getMonthName(int monthIndex) {
         return new DateFormatSymbols().getMonths()[monthIndex].toString();
    }

or if you wanted to create a better error than an ArrayIndexOutOfBoundsException:

	public static String getMonthName(int monthIndex) {
	    //since this is zero based, 11 = December
        if (monthIndex < 0 || monthIndex > 11 ) {
    	    throw new IllegalArgumentException(monthIndex + " is not a valid month index.");
        }
        return new DateFormatSymbols().getMonths()[monthIndex].toString();
    }

Solution 6 - Java

import java.time.Month;

Month exemple = new Month.of(12);
//---return a Month object with value of December---

String month = exemple.toString();
//---if you want to convert Month to String---

Solution 7 - Java

DateFormatSymbols class provides methods for our ease use.

To get short month strings. For example: "Jan", "Feb", etc.

getShortMonths()

To get month strings. For example: "January", "February", etc.

getMonths()

Sample code to return month string in mmm format,

private static String getShortMonthFromNumber(int month){
    if(month<0 || month>11){
        return "";
    }
    return new DateFormatSymbols().getShortMonths()[month];
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionshinynewbikeView Question on Stackoverflow
Solution 1 - JavaFlashView Answer on Stackoverflow
Solution 2 - JavaAbhishek ShahView Answer on Stackoverflow
Solution 3 - JavaHarry JoyView Answer on Stackoverflow
Solution 4 - JavaedgarmtzeView Answer on Stackoverflow
Solution 5 - JavaAS4noobView Answer on Stackoverflow
Solution 6 - JavaMurillo TavaresView Answer on Stackoverflow
Solution 7 - JavaManikandanView Answer on Stackoverflow