Paul Esteban Milan
Paul Esteban Milan

Reputation: 109

Calendar.MONTH setting to wrong month

 //this month
        SimpleDateFormat df_formonth = new SimpleDateFormat("MMM");
        c.set(Calendar.MONTH, 5); //integer to be changed upon click - maybe month counter from now
        String currmonth = df_formonth.format(c.getTime());     

This should return June since we index months from 0 to 11

but it returns july

any solutions or other ways to fix this?

Upvotes: 0

Views: 983

Answers (3)

You can try the following:

Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int day = cal.get(Calendar.DAY_OF_MONTH);
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.MONTH, Calendar.JUNE);

Upvotes: -1

alex.b
alex.b

Reputation: 1528

Well known issue when you are working with dates at the end of the month (31st of Aug). You should explicitly set the date.

For example read here for details: http://www.coderanch.com/t/385083/java/java/java-util-Calendar-set

Upvotes: 0

Reimeus
Reimeus

Reputation: 159774

Because today's date is the 31st of August and June only has 30 days, the month is automatically incremented to the following month giving July.

To solve you can set the date before setting the month

c.set(Calendar.DATE, 30);
c.set(Calendar.MONTH, Calendar.JUNE);

Also I suggest using Calendar constants for clarity

Upvotes: 6

Related Questions