Reputation: 7519
How do I convert a month string to integer?
On click method I want to display the date which is selected but if the date has an event it should display something more about the event. The method to check for the holiday event requires integer values.
Here's the code:
UPDATED:
@Override
public void onClick(View view)
{
int m = 0;
int d, y;
String date_month_year = (String) view.getTag();
selectedDayMonthYearButton.setText("Selected: " + date_month_year);
String [] dateAr = date_month_year.split("-");
Log.d(tag, "Date Split: " + dateAr[0] + " " + dateAr[1] + " " + dateAr[2]);
y = Integer.parseInt(dateAr[2]);
try {
Calendar c1 = Calendar.getInstance();
c1.setTime(new SimpleDateFormat("MMM").parse(dateAr[1]));
m = c1.get((Calendar.MONTH) + 1);
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//int m = Integer.parseInt(dateAr[1]);
d = Integer.parseInt(dateAr[0]);
Log.d(tag, "Date forward: " + d + " " + m + " " + y);
if (isHoliday(d, m, y))
{
Intent i = new Intent(view.getContext(), HijriEvents.class);
i.putExtra("date_string", date_month_year);
startActivity(i);
}
try
{
Date parsedDate = dateFormatter.parse(date_month_year);
Log.d(tag, "Parsed Date: " + parsedDate.toString());
}
catch (ParseException e)
{
e.printStackTrace();
}
}
public Boolean isHoliday(int d, int m, int y)
{
HijriCalendar hijri = new HijriCalendar(y, m, d);
if (!hijri.checkIfHoliday().contentEquals(""))
return true;
return false;
}
Upvotes: 3
Views: 9930
Reputation: 340108
Enum.valueOf( java.time.Month.class , "JANUARY" ).getValue()
1
See this run at Ideone.com.
Or just java.time.Month.valueOf( "JANUARY" )
. run at Ideone.com.
If the month is in the title case, as is usual in English, java.time.format.DateTimeFormatter.ofPattern( "MMMM", Locale.ENGLISH ).parse( "January", java.time.Month::from))
yields the JANUARY
enum constant. run at Ideone.com.
In modern Java, use only java.time classes, never Calendar
, Date
, SimpleDateFormat
, etc.
Turn your English month name into an enum object of type java.time.Month
. The trick is use Enum.valueOf
method to look up the enum object by name.
Month month = Enum.valueOf ( Month.class , "JANUARY" ) ;
To get the number 1-12 for January-December, ask for the value of the enum object, its ordinal position within the declaration list of enum objects. Call Month#getValue
.
int monthNumber = month.getValue() ;
Upvotes: 1
Reputation: 240966
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("MMM").parse("July"));
int monthInt = cal.get(Calendar.MONTH) + 1;
See
Upvotes: 13
Reputation: 6145
There are only 12 month, so just normalize the string and just do string comparison. I wouldn't try to over-optimize.
Upvotes: 1