Convert Month Name to Number in Java

In this post, we will see how to convert Month name to number in Java.

Please note that we will use first three letter of month name (First letter as capital) to convert it to Number.

There are multiple ways to convert month name to number in java. Let’s go through.

Using DateTimeFormatter and TemporalAccessor

If you are using Java 8 and above, this is preferred solution.

  • Create DateTimeFormatter object with given local and MMM as pattern.
  • Parse given monthName using DateTimeFormatter’s parse() method and get TemporalAccessor object.
  • Get month number using get(ChronoField.MONTH_OF_YEAR) method of TemporalAccessor.

Output

Using Calendar class with SimpleDateFormat

You can use SimpleDateFormat to convert MonthName to Date object and set Date to Calendar instance and use Calendar.get() method to get month number.

You can specify Locale as per your requirements.

Please note that Calendar class follows 0th based month index.
0 for January
1 for Febuary


11 for December

Output

If you want to number from 1 to 12, you can simply add 1 at highlight line in above code.

Using Month enum [ Java 8]

If you are interest only in English locale, you can use Month ENUM to get month number.

Output

Please note that you need to pass complete month name such as SEPTEMBER for Month enum.

That’s all about how to convert Month name to number in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *