Reputation: 1336
line
holds month name given by the user. I would like to display the month number.
example: june -> 6
Present code:
String line="june";
int monthNo = Integer.parseInt(GregorianCalendar.class.getField(line.toUpperCase()).get(line))+1;
System.out.println(monthNo);
What is the best method to do this?
Edit:
Using existing Calender classes
Upvotes: 2
Views: 790
Reputation: 21521
I suggest you use a combobox, or a control that restrain your users from typing anything, and mapping it to a constant field.
Then you can use from the GregorianCalendar
int selectedMonth = c.get(Calendar.MONTH) + 1;
(+1 since indexing starts at 0)
(c
being an instance of GregorianCalendar)
Upvotes: 4
Reputation: 4588
Just for the sake of doing this with Calendar
I shall offer this solution.
DateFormat df = new SimpleDateFormat("MMMM");
try {
Date date = df.parse("july");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.print(cal.get(Calendar.MONTH));
} catch (Exception e){
}
Note that this is not the best way of doing this at all and I'd suggest you use an enum instead.
Upvotes: 3
Reputation: 44067
Java's calendar API is not the best API around. Many people therefore changed to use http://www.joda.org/joda-time/ as a quasi alternative standard. But if your application is that simple, I think hard-coding a map of names pointing to numbers would be the easiest and most efficient solution (assuming, your string is in fact a user input, otherwise, use an enum as suggested). Alternatively, you can use a date format.
Upvotes: 2