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

前端 未结 4 1213
说谎
说谎 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);
        }
    

提交回复
热议问题