简体   繁体   中英

Day and month incorrect when setting next day of date using Calendar

//fetch date and convert to date type
String DateString = Integer.toString(getDay()) + "/" + Integer.toString(getMonth()) + "/" + Integer.toString(getYear());
DateFormat parser = new SimpleDateFormat("dd/MM/yyyy"); //current format of date
Date date = (Date) parser.parse(DateString); //convert string to date
//calculate next day
Calendar cal = Calendar.getInstance();
cal.setTime(date); //set calendar time to chosen date
cal.add(Calendar.DATE, 1); //add 1 day to calendar date
//set object to next day
parser.format(cal.getTime()); //set format to dd/MM/yyyy
setDay(cal.get(cal.DAY_OF_MONTH));
setMonth(cal.get(cal.MONTH));
setYear(cal.get(cal.YEAR));

I set a date to 23 October 2002. I want to set it to the next day using the above method. It shows 24 September 2002 instead of 24 October 2002. Why is it adding 1 to the day and removing 1 from the month?

The reason is that months are zero based index ie, they start from 0 instead of 1 so January is 0, Feb is 1, march is 2 and .....Decemeber is 11

From the Oracle docs :

A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.

EDIT:-

Trying to give the reason for why months start with zero. The tm structure which is defined in time.h has an integer field tm_mon with the range of 0-11, so I guess this has been taken from the C language. One other reason which might sound wierd but can be reason that since we have names of the month but for days(1,2,3...30,31) we dont have any names

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