Search code examples
javadate-arithmeticgregorian-calendar

Why are days not adding correctly to my date?


I am trying to add a random number of days to the date January 1, 2010 to make the new date fall between then and today (December 2, 2013). The total number of days between the two dates is 1431. I Googled how to do this, and found to add hours, you need only use HOUR field. However, when I try to use the DATE field, I get years way out of the expected range.

import java.util.Random;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class DateArithmetic{
    public static void main(String[] args){
            Random random = new Random();
            Calendar gc = new GregorianCalendar(2010, Calendar.JANUARY, 1, 0, 0, 1);

            System.out.println(gc.getTime());

            for(int i=0; i<100; i++){
                    gc.add(GregorianCalendar.DATE, random.nextInt(1431));
                    System.out.println(gc.getTime());
            }
    }
}

Solution

  • You are adding a random number of days 100 times to the same Calendar object. It makes sense that it would almost immediately advance well past today into the future.

    Re-initialize your GregorianCalendar object on each loop to the initial date.