111

Is there a oneliner to get the name of the month when we know:

int monthNumber  = calendar.get(Calendar.MONTH)

Or what is the easiest way?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
ogzd
  • 5,532
  • 2
  • 26
  • 27
  • 3
    @anyone_reaching_this_issue : This question (http://stackoverflow.com/questions/6192781/month-name-as-a-string) mentions getDisplayName() and other intesreting tricks – Poutrathor Oct 21 '14 at 09:03

22 Answers22

211

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()));
Nimantha
  • 6,405
  • 6
  • 28
  • 69
PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • 1
    This will work but I would like to get the string repr. of the month when I know the index of it. I think I will use the other approaches, thanks. – ogzd Feb 12 '13 at 12:15
  • 54
    this helped me to get the current month name. although i used ("MMMM") to get the full month name instead of a shortened one. – speedynomads Jun 02 '13 at 11:00
103
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;
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
subodh
  • 6,136
  • 12
  • 51
  • 73
  • 6
    DateFormatSymbols implementation was changed in JDK 8, so getMonths method doesn't return correct values for all Locale's anymore: http://www.oracle.com/technetwork/java/javase/8-compatibility-guide-2156366.html – ahaaman Apr 10 '14 at 12:32
  • 1
    could you give a workaround/working solution for JDK8? – Dominik May 13 '14 at 09:31
  • when would you get a month as a number? – Mickey Perlstein Nov 02 '17 at 11:01
  • Mickey to answer your question, here is how you get month as int and use it - public static void main(String[] args) { int month; GregorianCalendar date = new GregorianCalendar(); month = date.get(Calendar.MONTH); System.out.println("Current month is " + (month + 1) + " and Month name is " + getMonthForInt(month)); } static 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; } – Ajay Kumar Nov 29 '18 at 17:36
83

As simple as this

mCalendar = Calendar.getInstance();    
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
sandalone
  • 41,141
  • 63
  • 222
  • 338
  • 4
    The use of Calendar abstraction is the most elegant solution in my opinion. +1 – sebastian Apr 23 '15 at 13:05
  • 6
    Wrong! The problem will be in languages with cases. For example, in Slavic locales it will return month in genitive case, for example, for October in ru-RU locale you will receive `октября` instead of `Октябрь`, which you probably expect. – Nick Sikrier Nov 04 '17 at 18:37
42

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.

Terry Chern
  • 694
  • 1
  • 8
  • 15
  • 2
    This is useful for me `new SimpleDateFormat("MMMM").format(cal.getTime());` – Pratik Butani Oct 14 '14 at 13:07
  • this is a weak solution, how about jan, feb etc. not addition to January February etc. this will not cover all the situation – Abeer zaroor Apr 10 '16 at 20:01
  • 2
    Well, you should add 1 to the month. Arrays start from 0. – RoccoDev Aug 14 '16 at 14:19
  • this is bad, you are re-inventing java ? – Mickey Perlstein Nov 02 '17 at 10:58
  • 2
    This works for english speaking users. What about the others? – Advait Saravade Nov 13 '18 at 21:42
  • 1
    @MickeyPerlstein No. That's not 'reinventing' (as you put it) Java. And it's not 'bad' either. That's simply a way to do it. Besides that this is based on not having to use the Calendar class (or at least you don't have to use it - though if you want the current month maybe so) which might be desirable in some cases. Sure it's only for English but that's besides the point. – Pryftan Jun 26 '20 at 16:09
  • @Pryftan you're right I meant reinventing the operating system locales and creating a mirror based on your english language. good luck localizing that mess – Mickey Perlstein Nov 05 '20 at 14:23
40

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
Zoe
  • 27,060
  • 21
  • 118
  • 148
Eng. Samer T
  • 6,465
  • 6
  • 36
  • 43
17
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:

январь

artkoenig
  • 7,117
  • 2
  • 40
  • 61
  • Is a correct answer for RU locale. Very weird tho, that android SDK does not contain 'LLLL' spec. – Anfet Feb 04 '19 at 10:29
12

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 );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
11

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()
    );
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
10

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.

georger
  • 1,568
  • 21
  • 24
4

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,...
Samet ÖZTOPRAK
  • 3,112
  • 3
  • 32
  • 33
3

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));
}
ashokramcse
  • 2,841
  • 2
  • 19
  • 41
JibinNajeeb
  • 784
  • 1
  • 10
  • 31
  • doesn't `Month` start its index with January = 1, whereas Calendar starts with January = 0? Wouldn't `Month.of(calendar.get(Calendar.MONTH));` fail in the case of january? – MCO Jan 09 '20 at 10:17
2

You can get it one line like this:

String monthName = new DateFormatSymbols().getMonths()[cal.get(Calendar.MONTH)];
Whirvis
  • 189
  • 4
  • 23
2

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);
jhpg
  • 397
  • 3
  • 9
2

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
kushal Baldev
  • 729
  • 1
  • 14
  • 37
2
Calender cal = Calendar.getInstance(Locale.ENGLISH)
String[] mons = new DateFormatSymbols(Locale.ENGLISH).getShortMonths();
int m = cal.get(Calendar.MONTH);
String mName = mons[m];
Milad jalali
  • 622
  • 9
  • 10
2

Easiest Way

import java.text.DateFormatSymbols;

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

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

String englishMonth (int month){
        return Month.of(month);
    }
mxhc
  • 29
  • 1
  • Simple and direct suggestion, thanks. Your code doesn’t compile. You will either have to declare the return type `Month` or apply `toString` to the result before returning it. – Ole V.V. Jun 29 '18 at 10:30
1

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]
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Felipe Castilhos
  • 766
  • 1
  • 8
  • 18
1
import java.text.SimpleDateFormat;
import java.util.Calendar;


Calendar cal = Calendar.getInstance();
String currentdate=new SimpleDateFormat("dd-MMM").format(cal.getTime());
Nimantha
  • 6,405
  • 6
  • 28
  • 69
mahadev gouda
  • 119
  • 4
  • 9
0
DateFormat date =  new SimpleDateFormat("dd/MMM/yyyy");
Date date1 = new Date();
System.out.println(date.format(date1));
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
  • 1
    While your answer may be correct, it is of bad quality. Please elaborate on why this answer is correct. – SubliemeSiem Oct 10 '16 at 06:48
  • 1
    @SubliemeSiem I'm just trying to change format and simplest way to get it done: MM- it will return month name in integer like 01, 02, 03. MMM-it will return month name in short like jan, feb,mar. MMMM-it will return full month name in string format like January. – Amit Mishra Oct 10 '16 at 07:17
  • this is the only *CORRECT* answer for formatting dates. use a Date or Calendar object and format it with a formatter. the question itself is *BAD* – Mickey Perlstein Nov 02 '17 at 11:02
0

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()
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Junaid Bashir
  • 152
  • 3
  • 15
-3

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>
Rafael Sanches
  • 1,823
  • 21
  • 28