userJP userJP - 5 months ago 17
Android Question

Get current month full name in android

In my project, i have a spinner for choose month and I want to display current month as default selected. I have string array in

string.xml
.

<string-array name="Months">
<item>January</item>
<item>February</item>
<item>March</item>
<item>April</item>
<item>May</item>
<item>June</item>
<item>July</item>
<item>August</item>
<item>September</item>
<item>October</item>
<item>November</item>
<item>December</item>
</string-array>


In MainActivity, I set adapter to the spinner,

ArrayAdapter<CharSequence> monthAdapter = ArrayAdapter
.createFromResource(this, R.array.Months, R.layout.spinner_item);
monthAdapter.setDropDownViewResource(R.layout.spinner_item);
spnMonth.setAdapter(monthAdapter);
spnMonth.setSelection(Util.setCurrentMonthSpinner(context));


In
Util.java
I use these two functions, these function are static because the functions are used in many activities.

public static int setCurrentMonthSpinner (Context context) {
String[] months = context.getResources().getStringArray(R.array.Months);
for (int i = 0; i < months.length; i++) {
String mnth = Util.getCurrentMonth();
if (months[i].equals(mnth))
return i;
}
return 0;
}


and second method is...

public static String getCurrentMonth () {
Calendar cal = Calendar.getInstance();
SimpleDateFormat month_date = new SimpleDateFormat("MMMMMM");

return month_date.format(cal.getTime());
}


The method getCurrentMonth returns current month name like Jan or Feb but i want to get return String like January or February. Guide me...

Answer

Try adding a locale to your SimpleDateFormat like this:

SimpleDateFormat month_date = new SimpleDateFormat("MMMM", Locale.US);
Comments