简体   繁体   中英

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?

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

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM