Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get month number from month name

Tags:

java

date

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!

like image 870
Dmitry Avatar asked Jun 22 '14 20:06

Dmitry


People also ask

How do I extract month number from month name?

=TEXT(A2, "m") - returns a month number without a leading zero, as 1 - 12. =TEXT(A2,"mm") - returns a month number with a leading zero, as 01 - 12.

How do I convert month name to number?

Select the cells containing the month names that you want to convert. Press CTRL+1 from your keyboard or right-click and select “Format Cells” from the context menu that appears. This will open the Format Cells dialog box. Click on the Number tab and select “Custom” from the list under Category.


1 Answers

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()));
like image 147
Matt3o12 Avatar answered Oct 14 '22 05:10

Matt3o12