如何从日历中获取月份名称?

当我们知道:

int monthNumber  = calendar.get(Calendar.MONTH)

或者最简单的方法是什么?

288996 次浏览

You can achieve it using SimpleDateFormat, which is meant to format date and times:

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));
String getMonthForInt(int num) {
String month = "wrong";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (num >= 0 && num <= 11) {
month = months[num];
}
return month;
}

Joda-Time

How about using Joda-Time. It's a far better date-time API to work with (And January means january here. It's not like Calendar, which uses 0-based index for months).

You can use AbstractDateTime#toString( pattern ) method to format the date in specified format:

DateTime date = DateTime.now();
String month = date.toString("MMM");

Month Name From Number

If you want month name for a particular month number, you can do it like this:

int month = 3;
String monthName = DateTime.now().withMonthOfYear(month).toString("MMM");

Localize

The above approach uses your JVM’s current default Locale for the language of the month name. You want to specify a Locale object instead.

String month = date.toString( "MMM", Locale.CANADA_FRENCH );

This is the solution I came up with for a class project:

public static String theMonth(int month){
String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
return monthNames[month];
}

The number you pass in comes from a Calendar.MONTH call.

As simple as this

mCalendar = Calendar.getInstance();
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );

For some languages (e.g. Russian) this is the only correct way to get the stand-alone month names.

This is what you get, if you use getDisplayName from the Calendar or DateFormatSymbols for January:

января (which is correct for a complete date string: "10 января, 2014")

but in case of a stand-alone month name you would expect:

январь

If you have multi-language interface, you can use getDisplayName to display the name of month with control of displaying language.

Here is an example of displaying the month name in English, French, Arabic and Arabic in specific country like "Syria":

Calendar c = Calendar.getInstance();
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRANCE ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar") ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar", "SY") ) );
System.out.println(c.getTime().toString());

The result is:

January
janvier
يناير
كانون الثاني
Sat Jan 17 19:31:30 EET 2015

You can get it one line like this:

String monthName = new DataFormatSymbols.getMonths()[cal.get(Calendar.MONTH)]

This works for me:

String getMonthName(int monthNumber) {
String[] months = new DateFormatSymbols().getMonths();
int n = monthNumber-1;
return (n >= 0 && n <= 11) ? months[n] : "wrong number";
}

To returns "September" with one line:

String month = getMonthName(9);
DateFormat date =  new SimpleDateFormat("dd/MMM/yyyy");
Date date1 = new Date();
System.out.println(date.format(date1));

from the SimpleDateFormat java doc:

*         <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
*         <td><code>02001.July.04 AD 12:08 PM</code>
*         <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
*         <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>

It might be an old question, but as a one liner to get the name of the month when we know the indices, I used

String month = new DateFormatSymbols().getMonths()[monthNumber - 1];

or for short names

String month = new DateFormatSymbols().getShortMonths()[monthNumber - 1];

Please be aware that your monthNumber starts counting from 1 while any of the methods above returns an array so you need to start counting from 0.

Month::getDisplayName

Since Java 8, use the Month enum. The getDisplayName method automatically localizes the name of the month.

Pass:

  • A TextStyle to determine how long or how abbreviated.
  • A Locale to specify the human language used in translation, and the cultural norms used for abbreviation, punctuation, etc.

Example:

public static String getMonthStandaloneName(Month month) {
return month.getDisplayName(
TextStyle.FULL_STANDALONE,
Locale.getDefault()
);
}

This code has language support. I had used them in Android App.

String[] mons = new DateFormatSymbols().getShortMonths();//Jan,Feb,Mar,...


String[] months = new DateFormatSymbols().getMonths();//January,Februaty,March,...

It returns English name of the month. 04 returns APRIL and so on.

String englishMonth (int month){
return Month.of(month);
}

One way:

We have Month API in Java (java.time.Month). We can get by using Month.of(month);

Here, the Month are indexed as numbers so either you can provide by Month.JANUARY or provide an index in the above API such as 1, 2, 3, 4.

Second way:

ZonedDateTime.now().getMonth();

This is available in java.time.ZonedDateTime.

I created a Kotlin extension based on responses in this topic and using the DateFormatSymbols answers you get a localized response.

fun Date.toCalendar(): Calendar {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar
}




fun Date.getMonthName(): String {
val month = toCalendar()[Calendar.MONTH]
val dfs = DateFormatSymbols()
val months = dfs.months
return months[month]
}
import java.text.SimpleDateFormat;
import java.util.Calendar;




Calendar cal = Calendar.getInstance();
String currentdate=new SimpleDateFormat("dd-MMM").format(cal.getTime());

I found this much easier(https://docs.oracle.com/javase/tutorial/datetime/iso/enum.html)

private void getCalendarMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Month month = Month.of(calendar.get(Calendar.MONTH));
Locale locale = Locale.getDefault();
System.out.println(month.getDisplayName(TextStyle.FULL, locale));
System.out.println(month.getDisplayName(TextStyle.NARROW, locale));
System.out.println(month.getDisplayName(TextStyle.SHORT, locale));
}
Calender cal = Calendar.getInstance(Locale.ENGLISH)
String[] mons = new DateFormatSymbols(Locale.ENGLISH).getShortMonths();
int m = cal.get(Calendar.MONTH);
String mName = mons[m];

Easiest Way

import java.text.DateFormatSymbols;


int month = 3; // March
System.out.println(new DateFormatSymbols().getMonths()[month-1]);

For full name of month:

val calendar = Calendar.getInstance()
calendar.timeInMillis = date
return calendar.getDisplayName(Calendar.MONTH, Calendar.Long, Locale.ENGLISH)!!.toString()

And for short name of month:

val calendar = Calendar.getInstance()
calendar.timeInMillis = date
return calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.ENGLISH)!!.toString()