Calendar add () vs roll () when do we use it?

I know that add() adds a specified (signed) amount of time to a given time field based on calendar rules.

And roll() adds the specified (signed) unit of time to the given time field without changing large fields.

I can’t think about the everyday use of roll() , I would do everything on add() .

Can you help me with examples when we use roll() and when add() ?

EDIT 1

Replies Joda not accepted!

+48
java calendar
Mar 23
source share
4 answers
  • add() - almost always, as you said
  • roll() - for example, you want to "distribute" events in one month. The algorithm may be to continue for several days and post an event, and then continue. When the end of the month is reached, it should start from the very beginning. Therefore, roll() .
+48
Mar 23
source share

Found in jGuru

  • Calendar.roll ()
    Changes a certain unit and leaves "more" (in terms of time-month "more" than a day) units without changes. An example API is that with a date of August 31, 1999, (Calendar.MONTH, 8) gives April 30, 1999. That is, DAY has been changed according to the April maximum, but the β€œbig” unit, YEAR, was unchanged.

roll(): Rolls up 8 months here ie, adding 8 months to Aug will result in Apr but year remains unchanged(untouched).

  • Calendar.add ()
    Call the next "big" block to change, if necessary. That is, given the date of August 31, 1999, add (Calendar.MONTH, 8) gives April 30, 2000. add () also forces the milliseconds and all fields to be counted.

add(): Adds months to the current date ie, adding 8 months to Aug will give Apr of Next Year, hence forces the Year change.

+24
Mar 23 '10 at 23:27
source share

I just asked the same question (that’s how I found this page), and someone at my workplace (well done, DCK) came up with a suggestion:

The date selector on many smartphones (and other similar interfaces) will β€œroll” the day from the 31st to the 1st, without changing the month, similarly for the month field.

I can’t think of another use ATM, and this could be implemented in other ways, but at least this is an example!

Tim

+6
Feb 20 2018-12-12T00:
source share

Here is an example that won't work. The condition in the cycle will never be satisfied, because the throw, having reached January 31, 2014, will return to January 1, 2014.

  Calendar start=new GregorianCalendar(); start.set(Calendar.YEAR, 2014); start.set(Calendar.MONTH, 0); start.set(Calendar.DAY_OF_MONTH, 1); //January 2, 2014 Calendar end=new GregorianCalendar(); end.set(Calendar.YEAR, 2014); end.set(Calendar.MONTH, 1); end.set(Calendar.DAY_OF_MONTH, 2); //February 2, 2014 while (start.getTime().before(end.getTime())){ start.roll(Calendar.DATE, 1); } 
+2
Feb 07 '14 at 6:12
source share



All Articles