Convert Month String to Integer in Java
64,867
Solution 1
An alternative to SimpleDateFormat using Joda time:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
...
// if default locale is ok simply omit '.withLocale(...)'
DateTimeFormatter format = DateTimeFormat.forPattern("MMM");
DateTime instance = format.withLocale(Locale.FRENCH).parseDateTime("août");
int month_number = instance.getMonthOfYear();
String month_text = instance.monthOfYear().getAsText(Locale.ENGLISH);
System.out.println( "Month Number: " + month_number );
System.out.println( "Month Text: " + month_text );
OUTPUT:
Month Number: 8
Month Text: August
Solution 2
You could parse the month using SimpleDateFormat:
Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse("Feb");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
System.out.println(month == Calendar.FEBRUARY);
Be careful comparing int month
to an int (it does not equal 2!). Safest is to compare them using Calendar
's static fields (like Calendar.FEBRUARY
).
Solution 3
Java 8 solution:
DateTimeFormatter parser = DateTimeFormatter.ofPattern("MMM")
.withLocale(Locale.ENGLISH);
TemporalAccessor accessor = parser.parse("Feb");
System.out.println(accessor.get(ChronoField.MONTH_OF_YEAR)); // prints 2
Solution 4
Solution 5
you could just set up a switch statment, something like this (below). I'm posting this in case anyone wants a simple, easy to understand solution I know I would have wanted it before I typed this up:
switch(input2) {
case "january":
case "jan":
input2 = "1";
break;
case "febuary":
case "feb":
input2 = "2";
break;
case "march":
case "mar":
input2 = "3";
break;
case "april":
case "apr":
input2 = "4";
break;
case "may":
input2 = "5";
break;
case "june":
case "jun":
input2 = "6";
break;
case "july":
case "jul":
input2 = "7";
break;
case "august":
case "aug":
input2 = "8";
break;
case "september":
case "sep":
case "sept":
input2 = "9";
break;
case "october":
case "oct":
input2 = "10";
break;
case "november":
case "nov":
input2 = "11";
break;
case "december":
case "dec":
input2 = "12";
break;
}
Author by
Dylan Cali
Updated on May 08, 2021Comments
-
Dylan Cali about 3 years
Given a month string such as:
"Feb" or "February"
Is there any core Java or third party library functionality that would allow you to convert this string to the corresponding month number in a locale agnostic way?