Is there a method that returns the name of the month by its number? That is something like this:

String nameOfMonth; nameOfMonth = someMethod(1); System.out.println(nameOfMonth);// January 

I understand that you can write your own method, but I would like to know about the existing one.

3 answers 3

Too complicated answers are coming. Here is the simplest thing you can think of:

 System.out.println(Month.of(1)); // Вернёт JANUARY 

You can localize as easily:

 Month jan = Month.of(1); Locale loc = Locale.forLanguageTag("ru"); System.out.println(jan.getDisplayName(TextStyle.FULL_STANDALONE, loc)); // Вернёт Январь 

    Try to go from this side:

     public Date dt; dt = new Date(2000, 1, 1); System.out.println(dt.toGMTString()); 

    get: 1 Feb 3900 00:00:00 GMT .

    Then you can take a substring.

    Although for your task it will probably be easier to write your own method, which will return the name by number.

      There is a method to get the required through the java.util.Calendar class and its instances (see Calendar.getInstance() ). Next, set the month for the getDisplayName() and request getDisplayName() with the correct locale (see Calendar.getAvailableLocales() ).

      In the java.util.Date class, the corresponding methods are declared deprecated, i.e. they will no longer be supported in the future, so it’s right to use Calendar right away.

      Total the following will turn out:

       String getNameOfMonth(int month, Locale locale) throws IllegalArgumentException { Calendar c; String s; try { c=Calendar.getInstance(); c.set(Calendar.MONTH,month); s=c.getDisplayName(Calendar.MONTH,Calendar.LONG,locale); } catch (java.lang.NullPointerException ex) { s=null; } finally { // TODO finalize c } return s; } 

      It should be noted that it is desirable to transfer months converted to Calendar.JANUARY , etc., since in Java this constant is zero, i.e. the naive code System.out.println(getNameOfMonth(1,locale)); will return February.