I have this.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String monthName = br.readLine();
How to get month number which contain in monthName variable? Thanks!
I have this.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String monthName = br.readLine();
How to get month number which contain in monthName variable? Thanks!
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()));
Solution in Java 8 for English month names.
private int getMonthNumber(String monthName) {
return Month.valueOf(monthName.toUpperCase()).getValue();
}
Another approach using java.text.DateFormatSymbols
is this:
public static int monthAsNumber(
String month,
Locale locale,
boolean abbreviated,
boolean caseInsensitive
) {
DateFormatSymbols dfs = new DateFormatSymbols(locale);
String[] months = (abbreviated ? dfs.getShortMonths() : dfs.getMonths());
if (caseInsensitive) {
for (int i = 0; i < 12; i++) {
if (months[i].equalsIgnoreCase(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
} else {
for (int i = 0; i < 12; i++) {
if (months[i].equals(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
}
return -1; // no match
}
The proposed signature of seach method illustrates the many possible variations. Example:
System.out.println(monthAsNumber("MÄRZ", Locale.GERMANY, false, true));
// output: 2 (zero-based!)
If you want a month number starting with 1 then just add 1 to the result (more intuitive and also my recommendation).
Starting with Java 8 you have a new variation, too, namely stand-alone months. While in English these month names are identical in other languages they are not always identical (for example in Czech language "leden" (January) instead of "ledna"). To achieve these stand-alone forms you can use Month.getDisplayName(...) (not tested):
public static int monthAsNumber(
String month,
Locale locale,
boolean abbreviated,
boolean caseInsensitive,
boolean standAlone
) {
TextStyle style;
Month[] months = Month.values[];
if (abbreviated) {
style = standAlone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT;
} else {
style = standAlone ? TextStyle.FULL_STANDALONE : TextStyle.FULL;
}
if (caseInsensitive) {
for (int i = 0; i < 12; i++) {
if (months[i].getDisplayName(style, locale).equalsIgnoreCase(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
} else {
for (int i = 0; i < 12; i++) {
if (months[i].getDisplayName(style, locale).equals(month)) {
return i; // month index is zero-based as usual in old JDK pre 8!
}
}
}
return -1; // no match
}
If you have month name and you want integer number corresponding to that month try this
try{
Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(monthName);//put your month name in english here
Calendar cal = Calendar.getInstance();
cal.setTime(date);
monthNumber=cal.get(Calendar.MONTH);
System.out.println(monthNumber);
}
catch(Exception e)
{
e.printStackTrace();
}
Using Java 8 API
final DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern("MMM").withLocale(Locale.ENGLISH);
final TemporalAccessor temporalAccessor = dtFormatter.parse(month);
final int monthNumber = temporalAccessor.get(ChronoField.MONTH_OF_YEAR);
In March 2014, modern date-time API API supplanted the error-prone java.util
date-time API and their formatting API, SimpleDateFormat
. Since then it has been highly recommended to stop using the legacy API.
Solution using java.time
, the modern Date-Time API:
Use a DateTimeFormatter
with the pattern MMMM
to parse the given date. If the name of the month can be in different cases, you should build and use a case-insensitive DateTimeFormatter
.
Demo:
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
class Main {
public static void main(String[] args) {
// A sample month
String monthName = "March";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("MMMM", Locale.ENGLISH);
Month month = Month.from(parser.parse(monthName));
int monthNumber = month.getValue();
System.out.println(monthNumber);
// A case-insensitive formatter
DateTimeFormatter parserIgnoreCase = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("MMMM")
.toFormatter(Locale.ENGLISH);
System.out.println(Month.from(parserIgnoreCase.parse("march")).getValue());
}
}
Output:
3
3
Note: Never use SimpleDateFormat or DateTimeFormatter without a Locale.
Learn more about the modern Date-Time API from Trail: Date Time.