How can I convert an Integer to localized month name in Java?
import java.text.DateFormatSymbols;
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month-1];
}
Java get month string from integer
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).
Get month name from month number for a series of numbers
you can get String
description of a month from int
using 1) array of month or 2) own method.
Case 1:
String[] monthString = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
Later, in the code, you can call it like:
EXAMPLE:
for(int i=0; i<12; i++) {
System.out.println("Month: "+monthString[i]);
}
Assuming, we have case when we need to get month some times (5,4,3,2);
...(monthString[5], monthString[4], monthString[3], monthString[2]) ..
Case 2:
public String getMonth(int month){
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;
}
return monthString;
}
EXAMPLE:
for(int i=0; i<12; i++) {
System.out.println("Month: "+getMonth(i));
}
OUTPUT:
Month: January
Month: February
Month: March
Month: April
Month: May
Month: June
Month: July
Month: August
Month: September
Month: October
Month: November
Month: December
Can't convert int month to month name android java
I get only "Jan" for all months
Because String sdf = new SimpleDateFormat("LLL", Locale.getDefault()).format(monthOfYear);
here, monthOfYear
is Number Object so, DateFormate
class will convert it to Date
object from that number, which will be between 1 Jan, 1970
to 12 Jan, 1970
so you are always getting Jan for all month.
Try,
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, monthOfYear);
sdf = new SimpleDateFormat("LLL", Locale.getDefault()).format(calendar.getTime());
or
sdf = new DateFormatSymbols().getShortMonths()[monthOfYear];
DateFormat code snippet:
/**
* Formats the specified object as a string using the pattern of this date
* format and appends the string to the specified string buffer.
* <p>
* If the {@code field} member of {@code field} contains a value specifying
* a format field, then its {@code beginIndex} and {@code endIndex} members
* will be updated with the position of the first occurrence of this field
* in the formatted text.
*
* @param object
* the source object to format, must be a {@code Date} or a
* {@code Number}. If {@code object} is a number then a date is
* constructed using the {@code longValue()} of the number.
* @param buffer
* the target string buffer to append the formatted date/time to.
* @param field
* on input: an optional alignment field; on output: the offsets
* of the alignment field in the formatted text.
* @return the string buffer.
* @throws IllegalArgumentException
* if {@code object} is neither a {@code Date} nor a
* {@code Number} instance.
*/
@Override
public final StringBuffer format(Object object, StringBuffer buffer, FieldPosition field) {
if (object instanceof Date) {
return format((Date) object, buffer, field);
}
if (object instanceof Number) {
return format(new Date(((Number) object).longValue()), buffer, field);
}
throw new IllegalArgumentException("Bad class: " + object.getClass());
}
Get month number from month name
Use Java's Calendar class. It can parse any given string into a valid calendar instance.
Here is an example (assuming that the month is in english).
Date date = new SimpleDateFormat("MMMM", Locale.ENGLISH).parse(monthName);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
println(cal.get(Calendar.MONTH));
You can specify the language in SimpleDateFormat:
String monthName = "März"; // German for march
Date date = new SimpleDateFormat("MMMM", Locale.GERMAN).parse(monthName);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
println(cal.get(Calendar.MONTH));
By default, Java uses the user's local to parse the string.
Keep in mind that a computer starts counting at 0. So, January will be 0. If you want a human readable date, you should format the calendar instance:
SimpleDateFormat inputFormat = new SimpleDateFormat("MMMM");
Calendar cal = Calendar.getInstance();
cal.setTime(inputFormat.parse(monthName));
SimpleDateFormat outputFormat = new SimpleDateFormat("MM"); // 01-12
println(outputFormat.format(cal.getTime()));
Get name of the month in Java
The Calendar
class is not the best class to use when it comes obtaining the localized month name in one statement.
The following is an example of obtaining the month name of a desired month specified by a int
value (where January is 1), using only the Calendar
class:
// Month as a number.
int month = 1;
// Sets the Calendar instance to the desired month.
// The "-1" takes into account that Calendar counts months
// beginning from 0.
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, month - 1);
// This is to avoid the problem of having a day that is greater than the maximum of the
// month you set. c.getInstance() copies the whole current dateTime from system
// including day, if you execute this on the 30th of any month and set the Month to 1
// (February) getDisplayName will get you March as it automatically jumps to the next
// Month
c.set(Calendar.DAY_OF_MONTH, 1);
// Returns a String of the month name in the current locale.
c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
The above code will return the month name in the system locale.
If another locale is required, one can specify another Locale
by replacing the Locale.getDefault()
with a specific locale such as Locale.US
.
How to get full name of month from date in Java 8 while formatting
The string you are looking for is MMMM
.
Source: DateTimeFormatter Javadoc
SimpleDateFormat localized month names
Your problem has nothing to do with SimpleDateFormat
- you're just doing the wrong thing with the result.
You haven't told us what you're doing with the string afterwards - how you're displaying it in the UI - but that's the problem. You can see that it's fetching a localized string; it's only the display of the accented character which is causing a problem. You would see exactly the same thing if you had a string constant in there containing the same accented character.
I suggest you check all the encodings used throughout your app if it's a web app, or check the font you're displaying the string in if it's a console or Swing app.
If you examine the string in the debugger I'm sure you'll see it's got exactly the right characters - it's just how they're getting to the user which is the problem.
Related Topics
Differencebetween Cascade & Inverse in Hibernate, What Are They Used For
Karate Karate-Config.Js Not a Js Function
Differencebetween Declaration and Definition in Java
Differencebetween <Jsp:Include Page = ... > and <%@ Include File = ... >
How to Change Background Color of Jtabbedpane
In Java Critical Sections, What Should I Synchronize On
Can an Interface Extend Multiple Interfaces in Java
Could Not Serialize Object Cause of Hibernateproxy
What Are Shadow Variables in Java
Why Integer.Max_Value + 1 == Integer.Min_Value
Eclipse - Debugger Doesn't Stop at Breakpoint
Swing - Thread.Sleep() Stop Jtextfield.Settext() Working
Permutation Algorithm Without Recursion? Java
Attach the Source in Eclipse of a Jar
Superclass Reference Not Able to Call Subclass Method in Java
Is It Necessary to Close Each Nested Outputstream and Writer Separately