I\'m trying to return the name of the month as a String, for instance \"May\", \"September\", \"November\".
I tried:
int month = c.get(Calendar.MONTH
Russian.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
new Locale( "ru" , "RU" )
)
май
English in the United States.
Month
.MAY
.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.US
)
May
See this code run live at IdeOne.com.
Here’s the modern answer. When this question was asked in 2011, Calendar and GregorianCalendar were commonly used for dates and times even though they were always poorly designed. That’s 8 years ago now, and those classes are long outdated. Assuming you are not yet on API level 26, my suggestion is to use the ThreeTenABP library, which contains an Android adapted backport of java.time, the modern Java date and time API. java.time is so much nicer to work with.
Depending on your exact needs and situation there are two options:
Month and its getDisplayName method.DateTimeFormatter. Locale desiredLanguage = Locale.ENGLISH;
Month m = Month.MAY;
String monthName = m.getDisplayName(TextStyle.FULL, desiredLanguage);
System.out.println(monthName);
Output from this snippet is:
May
In a few languages it will make a difference whether you use TextStyle.FULL or TextStyle.FULL_STANDALONE. You will have to see, maybe check with your users, which of the two fits into your context.
If you’ve got a date with or without time of day, I find a DateTimeFormatter more practical. For example:
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM", desiredLanguage);
ZonedDateTime dateTime = ZonedDateTime.of(2019, 5, 31, 23, 49, 51, 0, ZoneId.of("America/Araguaina"));
String monthName = dateTime.format(monthFormatter);
I am showing the use of a ZonedDateTime, the closest replacement for the old Calendar class. The above code will work for a LocalDate, a LocalDateTime, MonthDay, OffsetDateTime and a YearMonth too.
What if you got a Calendar from a legacy API not yet upgraded to java.time? Convert to a ZonedDateTime and proceed as above:
Calendar c = getCalendarFromLegacyApi();
ZonedDateTime dateTime = DateTimeUtils.toZonedDateTime(c);
The rest is the same as before.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp with subpackages.java.time was first described.java.time to Java 6 and 7 (ThreeTen for JSR-310).