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

前端 未结 4 1182
说谎
说谎 2020-12-24 05:07

I know add() adds the specified (signed) amount of time to the given time field, based on the calendar\'s rules.

And roll() adds the specif

相关标签:
4条回答
  • 2020-12-24 05:32

    Here is an example that will not work. The condition in the loop will never be satisfied, because the roll, once reaching January 31, 2014, will go back 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);
        }
    
    0 讨论(0)
  • 2020-12-24 05:34

    I was just asking the same question (which is how I found this page) and someone at my work place (well done, DCK) came up with a suggestion:

    The date selectors on many smart phones (and other similar interfaces) will "roll" the day from the 31st to the 1st without altering the month, similarly for the month field.

    I can't think of another use ATM and this one could be implemented in other ways, but at least it's an example!

    Tim

    0 讨论(0)
  • 2020-12-24 05:40
    • add() - almost always, as you said
    • roll() - for example you want to "dispense" events in one month. The algorithm may be to proceed a number of days and place the event, then proceed further. When the end of the month is reached, it should start over from the beginning. Hence roll().
    0 讨论(0)
  • 2020-12-24 05:50

    Found in jGuru

    • Calendar.roll()
      Changes a specific unit and leaves 'larger' (in terms of time-month is 'larger' than day) units unchanged. The API example is that given a date of August 31, 1999, rolling by (Calendar.MONTH, 8) yields April 30, 1999. That is, the DAY was changed to meet April's maximum, but the 'larger' unit, YEAR, was unchanged.

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

    • Calendar.add()
      Will cause the next 'larger' unit to change, if necessary. That is, given a date of August 31, 1999, add(Calendar.MONTH, 8) yields April 30, 2000. add() also forces a recalculation of milliseconds and all fields.

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

    0 讨论(0)
提交回复
热议问题