I want to increase a certain date by 1 day. I create a Calendar object like:
Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 2012); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DAY_OF_MONTH, 31);
Then, for increasing it by 1 day, I can do 2 things :
cal.add(Calendar.DAY_OF_MONTH, 1);
OR
cal.add(Calendar.DAY_OF_YEAR, 1);
There are also other "DAY" constants, but I get the same result using the above 2 methods of increasing the day by 1. In which case will I get different results for the two?
DAY_OF_YEAR. Field number for get and set indicating the day number within the current year DAY_OF_MONTH. Field number for get and set indicating the day of the month. This is a synonym for DATE.
Calendar 's getInstance method returns a Calendar object whose calendar fields have been initialized with the current date and time: Calendar rightNow = Calendar.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With