If the Calendar is on the last day of the month (say 31st of July) , will
c.add(Calendar.DAY_OF_MONTH, 1);
set c to the start of the same month, July, or will it advance c to the next month, August?
Look at the documentation of the superclass java.util.Calendar
, in the section named " Field Manipulation " (emphasis mine):
add(f, delta)
addsdelta
to fieldf
. This is equivalent to callingset(f, get(f) + delta)
with two adjustments:Add rule 1 . The value of field
f
after the call minus the value of fieldf
before the call isdelta
, modulo any overflow that has occurred in fieldf
. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.
So add(Calendar.DAY_OF_MONTH, 1)
will change 31st of July to 1st of August .
In contrast, the documentation continues:
roll(f, delta)
addsdelta
to fieldf
without changing larger fields. This is equivalent to callingadd(f, delta)
with the following adjustment:Roll rule . Larger fields are unchanged after the call. A larger field represents a larger unit of time.
DAY_OF_MONTH
is a larger field thanHOUR
.
So roll(Calendar.DAY_OF_MONTH, 1)
will change 31st of July to 1st of July .
Months in Calendar object start from 0. so 1 means February. And you know february last day is 28 so output should be 2 March.
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
so
Calendar calendar = new GregorianCalendar();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // Jan = 0, not 1
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.