What's the difference between adding DAY_OF_MONTH or DAY_OF_YEAR to a Calendar object?
Solution 1:
For adding it really makes no difference, but this
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DAY_OF_YEAR));
prints
28
363
Solution 2:
Calendar.add
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.
Here you have a list of the fields of Calendar that you can add or subtract:
-
MILLISECOND
is the number of milliseconds between 0 and 999 -
SECOND
is the number of seconds between 0 and 59 -
MINUTE
is the number of minutes between 0 and 59 -
HOUR
is the number of hours between 0 and 11 -
HOUR_OF_DAY
is the number of hours between 0 and 23 -
DAY_OF_WEEK
is the day in relation of the week between 1 and 7 -
DAY_OF_MONTH
is the day in relation of the month between 1 and 31 -
DAY_OF_YEAR
is the day in relation of the year between 1 and 366 -
WEEK_OF_MONTH
is the week in relation of the month starting from 1 -
WEEK_OF_YEAR
is the week in relation of the year starting from 1 -
MONTH
is the month in relation of the year between 0 and 11 -
YEAR
is the number of years starting from 1
Hours, days and weeks have multiple fields but it doesn't matter which one you choose1. For example using -8 for DAY_OF_WEEK
will work.
calendar.add(Calendar.DAY_OF_MONTH, -2); // subtract 2 days
calendar.add(Calendar.DAY_OF_WEEK, -2); // subtract 2 days
calendar.add(Calendar.DAY_OF_YEAR, -2); // subtract 2 days
calendar.add(Calendar.YEAR, -2); // subtract 2 years
1It doesn't matter only using Calendar.add
, with other operations the results might be different.
Solution 3:
Use Calendar.DATE
for your purposes. In your case these three constants are synonyms.